Reputation: 427
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.
Upvotes: 1
Views: 4127
Reputation: 70297
The point of const generics is that the size of the array is known at compile-time. If you want a runtime-known size, then that's what Vec<T>
is for. Consider
fn foo<const C: usize>() -> [i32; C] {
[1; C]
}
Then call it as
foo::<3>();
Note that, by its nature, this forces you to only use constant values; if you try to put a local variable into the generic argument position, you'll get an error.
Upvotes: 7