Kyrielight
Kyrielight

Reputation: 103

How to print inside map function

I want to know the value of an parameter inside map for debugging purposes. I expected something like this to work but it doesn't.

let result = (0..5)
    .flat_map(|x| (0..=x - 1).map(move |y| (y, x)))
    .map(|(x, y)| println!("{:?}", x) input[x] + input[y])
    .collect::<Vec<i32>>();

Upvotes: 0

Views: 2148

Answers (1)

Netwave
Netwave

Reputation: 42678

Just create a new scope with braces ({}) inside the clusure:

|(x, y)| {
    println!("{:?}", x);
    input[x] + input[y]
}

As per your example:

fn main() {
    let input: Vec<_> = (0..100).collect();
    let _result = (0..5)
        .flat_map(|x| (0..x).map(move |y| (y, x)))
        .map(|(x, y)| {
            println!("{:?}", x);
            input[x] + input[y]
        })
        .collect::<Vec<i32>>();
}

Playground

Upvotes: 3

Related Questions