定义结构时如何使用特征中的常量?

How to use a constant from a trait when defining a struct?

以下代码:

use std::marker::PhantomData;

trait MyTrait {
    const FOO: usize;
}

struct MyStruct<T: MyTrait> {
    v: [u32; <T as MyTrait>::FOO],
    p: PhantomData<T>,
}

给我以下编译错误:

error[E0277]: the trait bound `T: MyTrait` is not satisfied
 --> src/lib.rs:8:14
  |
4 |     const FOO: usize;
  |     ----------------- required by `MyTrait::FOO`
...
7 | struct MyStruct<T: MyTrait> {
  |                 -- help: consider further restricting this bound: `T: MyTrait +`
8 |     v: [u32; <T as MyTrait>::FOO],
  |              ^^^^^^^^^^^^^^^^^^^ the trait `MyTrait` is not implemented for `T`

(Link to the playground)

如何在定义矢量时成功使用 FOO

目前,you can't

数组长度不能使用泛型参数。这是一个由常量和泛型在编译器中实现和交互的方式导致的问题,并且已经解决了几年,但改进缓慢。