Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

List Comprehension in Rust

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading