Sometimes its useful to create new values for a fixed size array in a loop:
fn foo(u: f64) -> [f64; 3] {
let mut ret = [-1.0; 3]; // -1 is never used!
for i in 0..3 {
ret[i] = some_calculation(u, i);
}
return ret;
}
While this works, it's a bit weak to create an array filled with a value which is never used.
An alternative is to manually unroll, but this isn't so nice for larger fixed sized arrays or when the expression is more involved then the example given:
fn foo(u: f64) -> [f64; 3] {
return [
some_calculation(u, 0),
some_calculation(u, 1),
some_calculation(u, 2),
];
}
Does Rust provide a way to do something roughly equivalent Python's list comprehension?
fn foo(u: f64) -> [f64; 3] {
return [some_calculation(u, i) for i in 0..3];
}
I am a beginner who has very little experience with iterators.