I am learning how to use const generics in rust. An easy demo like this: Playground
Can somebody tell me how to use a const generic array as a return type?
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]);
}
The compile message as following:
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.