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

1 Answer

0 votes
// Using a custom function that takes a callback

// Apply a callback to each element and return a new Vec
fn map_vec<F>(arr: &[i32], callback: F) -> Vec<i32>
where
    F: Fn(i32) -> i32,
{
    let mut result = Vec::new();

    for &item in arr {
        result.push(callback(item)); // apply the callback
    }

    result
}

// callback function: double the number
fn double(x: i32) -> i32 {
    x * 2
}

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

    let doubled = map_vec(&numbers, double);

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



/*
run:

[10, 20, 30, 40]

*/

 



answered Mar 21 by avibootz

Related questions

...