Transforming and Collecting into a Vector

vector, map, enumerate

Let’s assume we have a list of numbers, and we want to transform them into a list of structs:

#[derive(Debug)]
struct NumberInfo {
    id: usize,
    value: i32,
    is_even: bool,
}

fn main() {
    let numbers = vec![10, 15, 22, 33, 40];

    let info_list: Vec<NumberInfo> = numbers
        .into_iter()
        .enumerate()
        .map(|(id, value)| NumberInfo {
            id,
            value,
            is_even: value % 2 == 0,
        })
        .collect();

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

into_iter(): Consumes the original collection, turning it into an iterator.

enumerate(): Adds an index (id) to each item.

map(): Applies a closure to transform each item.

collect(): Gathers the transformed items into a collection (e.g., Vec).

The interesting part here is this:

is_even: value % 2 == 0,

This adds the missing piece of the jigsaw, the key:value pair required by the struct!

     Running `target/debug/vec_map`
[
    NumberInfo {
        id: 0,
        value: 10,
        is_even: true,
    },
    NumberInfo {
        id: 1,
        value: 15,
        is_even: false,
    },
    NumberInfo {
        id: 2,
        value: 22,
        is_even: true,
    },
    NumberInfo {
        id: 3,
        value: 33,
        is_even: false,
    },
    NumberInfo {
        id: 4,
        value: 40,
        is_even: true,
    },
]