Create a vector with the length of a variable or constant

Hey,

I'm new in Rust and I have a question: Can't I create a vector with the length of a variable or constant?

const n: u128 = 1000;
let memo: vec![0; n];

This causes an error I don't understand.

Thank you.

It’s just a syntax error :wink:

const n: u128 = 1000;
- let memo: vec![0; n];
+ let memo = vec![0; n];

well, and a type error, too, as the length of a vector needs to be a usize:

- const n: u128 = 1000;
+ const n: usize = 1000;
let memo = vec![0; n];

or

const n: u128 = 1000;
- let memo = vec![0; n];
+ let memo = vec![0; n as usize]; // this wraps/overflows if n is too big

Variables are fully supported, too

let n = 1000;
let memo = vec![0; n];
1 Like

Thank you so much.
It worked :slight_smile:

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.