How to apply a callback to an array (apply a function to each element) in Rust

3 Answers

0 votes
// Using a closure as the callback

fn main() {
    let numbers = [5, 10, 15, 20];

    let tripled = numbers.iter().map(|x| x * 3).collect::<Vec<_>>();

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


/*
run:

[15, 30, 45, 60]

*/

 



answered Mar 21 by avibootz
0 votes
// Using iter().map() 

fn main() {
    let numbers = [5, 10, 15, 20];

    let doubled: Vec<i32> = numbers
        .iter()
        .map(|x| x * 2)   // callback
        .collect();

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



/*
run:

[10, 20, 30, 40]

*/

 



answered Mar 21 by avibootz
0 votes
// Modify the array in place

fn for_each_mut<F>(arr: &mut [i32], mut callback: F)
where
    F: FnMut(i32) -> i32,
{
    for item in arr.iter_mut() {
        *item = callback(*item); // apply callback and update
    }
}

fn main() {
    let mut numbers = [5, 10, 15, 20];

    for_each_mut(&mut numbers, |x| x * 2);

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


/*
run:

[10, 20, 30, 40]

*/

 



answered Mar 21 by avibootz
...