Back to questions
JuniorTheoryCommon
What does the program print (lines separated by spaces)?
fn main() {
let v = vec![1, 2];
let it = v.iter().map(|x| {
println!("map {x}");
x * 2
});
println!("start");
let s: i32 = it.sum();
println!("{s}");
}start map 1 map 2 6
- Expecting
map 1 map 2beforestart, as from an eagermapin JavaScript: Rust'smaponly wraps the iterator, and its closure runs whensumpulls the elements. - Expecting a compile error because
itis notmut:sumtakes the iterator by value, so the binding itself never changes.
- What would the program print if the line with
sumwere removed? - In what order would the lines appear with a
filteradded aftermap?