如何避免特征中具有依赖关联常量的“不受约束的通用常量”?

Qua*_*ock 5 arrays constants rust

我正在编写一个具有两个关联常量的特征:第一个是 a usize,另一个是usize长度等于第一个常量的数组。本质上,我的特质相当于以下内容:

#![feature(const_trait_impl)]
#![feature(generic_const_exprs)]

trait Foo {
    const SIZE: usize;
    const ARR: [usize; Self::SIZE];
}

struct S;

impl const Foo for S {
    const SIZE: usize = 2;
    const ARR: [usize; Self::SIZE] = [1, 2];
}

fn main() {
    const TEST: &[usize; 2] = &S::ARR;
    println!("{:?}", TEST);
}
Run Code Online (Sandbox Code Playgroud)

截至当前的夜间构建,此特征定义会产生以下错误:

error: unconstrained generic constant
 --> src\main.rs:6:5
  |
6 |     const ARR: [usize; Self::SIZE];
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = help: try adding a `where` bound using this expression: `where [(); Self::SIZE]:`
Run Code Online (Sandbox Code Playgroud)

不幸的是,建议的修复没有用,因为where涉及的任何边界都Self::SIZE将是无限递归的。我准备放弃,直到我发现了一个似乎有效的替代方案:

error: unconstrained generic constant
 --> src\main.rs:6:5
  |
6 |     const ARR: [usize; Self::SIZE];
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = help: try adding a `where` bound using this expression: `where [(); Self::SIZE]:`
Run Code Online (Sandbox Code Playgroud)

考虑到所有因素,我对这种差异感到相当困惑。有什么办法可以解决这个问题,或者主要只是等待const语言支持改进吗?

Sta*_*Phy 1

您可以执行以下操作

trait Foo<const N : usize>{
    const ARR : [usize; N];
}

struct S;

impl Foo<2> for S{
    const ARR : [usize; 2] = [1, 2];
}

impl Foo<3> for S{
    const ARR : [usize; 3] = [1, 2, 3];
}

fn main(){
    const TEST : &[usize; 2] = &S::ARR;
    println!("{:?}", TEST);  // [1, 2]

    const TEST2 : &[usize; 3] = &S::ARR;
    println!("{:?}", TEST2);  // [1, 2, 3]
}
Run Code Online (Sandbox Code Playgroud)