Use iterator instead of for loop

How can I change the for loop with an iterator method(s)?

fn main() {
    let mut list = vec![1,2,3,4,5,4,5,3];
    let change = 3;

    for l in list.iter_mut() {
        if l == &change {
            *l += 5;
        }
    }

    println!("{:?}", list);
}

should be

   list.iter_mut().what_method().collect();

Use list.iter_mut().for_each(/* fn here */).

Is there no way of filtering the value(s) in the list, changing it, and collecting the new list (changed/unchanged)?
And not simply looping over it?

Well your original code didn't actually filter element. Is this is what you actually need, then use filter_map

Or if you need to retain unchanged elements as well, then use map
.

1 Like

Sorry about that. I mimicked the actual code in a sample app and forgot to add that part.

Something like this

let mut list = [1,2,3,4,5,4,5,3];
list.iter_mut()
    .for_each(
        |l| if *l == 3 {
            *l += 5;
        }
    );

UPD: Oh, you needed a new list… It must be something like this then:

let list = [1,2,3,4,5,4,5,3];
let list2 = list.iter()
    .map(
        |&l| if l == 3 {
             l + 5
        } else {
             l
        }
    )
    .collect::<Vec<i32>>();
2 Likes

Something like this?

list.iter().map(|&x| match x {
    3 => 8,
    i => i
}).collect::<Vec<_>>()
3 Likes

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.