How to define something like to the following C code
#define NUM 10
int a[N];
for (int i=0; i<N; ++i) {
a[i] = i+1;
}
For example, a is on the stack, which is possible because the size is known in compile time.
How to define something like to the following C code
#define NUM 10
int a[N];
for (int i=0; i<N; ++i) {
a[i] = i+1;
}
For example, a is on the stack, which is possible because the size is known in compile time.
This is how it could be done:
const N: usize = 10;
let mut a = [0; N];
for (i,x) in a.iter_mut().enumerate() {
*x = i+1;
}
println!("{:?}", a);
// prints: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Syntactically closer to your C code would be:
const N: usize = 10;
let mut a = [0; N];
for i in 0..N {
a[i] = i + 1;
}
println!("{:?}", a);
// prints: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Edit: Note that both examples create arrays of usize
, so an unsigned element type.
If you’re ok with a resizable vector instead of a fixed-length array, you could do something like this:
const N:usize = 10;
let a: Vec<i32> = (1..=N).collect();
Thanx a lot
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.