Back to questions
JuniorTheoryCommon
What does the program print?
fn main() {
let k = 3;
let add = |x| x + k;
let k = 10;
println!("{} {}", add(2), k);
}5 10
- Expecting
12 10, as in Python: the closure keeps thekthat existed when it was written, andlet k = 10adds a new variable instead of changing that one. - Expecting a compile error, as with a nested
fn(E0434): unlike a function, a closure can read the variables of the code around it.
- What happens if
kis declaredmutandlet k = 10;becomesk = 10;? - How would you write
addwith explicit parameter and return types?