In python if I have an array like [2, 4, 6] I can do the following
old_arr = [2, 4, 6]
new_arr = [x*2 for x in old_arr]
Is there a similar attribute in rust that will let me modify an array before returning it?
In Rust, iterators are used instead of comprehensions.
A very common pattern is .iter().map(...).collect()
.
.iter()
creates an iterator from a iterable data structure.map()
creates a new iterator over modified elements.collect()
stores all the elements back in a data structure.For example, to mimic your case:
fn main() {
let old_arr = vec![2, 4, 6];
let new_arr: Vec<i32> = old_arr.iter().map(|x| 2 * x).collect();
println!("old_arr: {:?}", old_arr);
println!("new_arr: {:?}", new_arr);
}
old_arr: [2, 4, 6]
new_arr: [4, 8, 12]
|x| 2 * x
is a closure.
Note that iterators in Rust are extremely fast, as they are mostly zero-cost abstractions.
In your special case, you could, however, also write:
fn main() {
let old_arr = [2, 4, 6];
let new_arr = old_arr.map(|x| 2 * x);
println!("old_arr: {:?}", old_arr);
println!("new_arr: {:?}", new_arr);
}
old_arr: [2, 4, 6]
new_arr: [4, 8, 12]
But that only works on arrays of constant size. For the general usecase, use vectors instead.