duck
duck

Reputation: 1904

How do I take multiple arguments in a closure and print them?

I have a call to env::vars_os and would like to print all of them in a functional manner:

env::vars_os()
    .map(|(k, v)| println!("k : {:?}, v : {:?} \n", k, v));

This prints nothing, but the article Destructuring and Pattern Matching indicates this should be possible.

Upvotes: 1

Views: 586

Answers (1)

paholg
paholg

Reputation: 2060

Looking at the documentation for vars_os(), we see that it is an iterator over tuples, which have the syntax (a, b). So, changing your code to

env::vars_os()
    .map(|(k, v)| println!("k : {:?}, v : {:?} \n", k, v));

should do the trick.

The syntax you are using would destructure into a struct, only you left out the struct's name, which would precede the curly braces.


Iterators in Rust are lazily evaluated, which means none of the code in the map is executed until the iterator is consumed. You can do this by calling collect(). However, the idiomatic way to do it would be to put code that has side-effects (such as printing) in a for loop instead of a map:

for (k, v) in env::vars_os() {
    println!("k : {:?}, v : {:?} \n", k, v);
}

Upvotes: 2

Related Questions