何时(如何)在Rust中使用const泛型?

我正在学习如何在 Rust 中使用 const 泛型。像这样的简单演示:Playground

有人能告诉我如何使用 const 泛型数组作为返回类型吗?

fn foo<const C: usize>(n: u32) -> [i32; C] {
    // failed
    // [1; 3]
    // failed
    [1; n]
}

fn hoo<const N: usize>(arr: [i32; N]) {
    println!("the array is {:?}", arr);
}

fn main() {
    // Give a number, create a array, this fails
    let f = foo(3);

    // const array as input
    hoo([1]);
    hoo([1, 2, 3]);
}

编译信息如下:

  Compiling playground v0.0.1 (/playground)
error[E0435]: attempt to use a non-constant value in a constant
 --> src/main.rs:2:9
  |
1 | fn foo<const C: usize>(n: u32) -> [i32; C] {
  |                        - this would need to be a `const`
2 |     [1; n]
  |         ^

error: aborting due to previous error

For more information about this error, try `rustc --explain E0435`.
error: could not compile `playground`

To learn more, run the command again with --verbose.

回答

const 泛型的要点是数组的大小在编译时是已知的。如果您想要运行时已知的大小,那么这就是Vec<T>目的。考虑

fn foo<const C: usize>() -> [i32; C] {
    [1; C]
}

然后称之为

foo::<3>();

请注意,就其性质而言,这迫使您只能使用常量值;如果您尝试将局部变量放入泛型参数位置,则会出现错误。


以上是何时(如何)在Rust中使用const泛型?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>