Back to questions
JuniorTheoryCommon
What happens when this program is built and run?
fn main() {
let mut count = 0;
let inc = || count += 1;
inc();
println!("{count}");
}It does not compile
- Expecting
1:let mut countis not enough, becauseincstores a mutable reference tocount, and calling it changes the closure, which therefore needslet mut inc. - Expecting the closure to change a copy and print
0: withoutmoveit borrowscountitself, and withlet mut incthe program would print 1.
- Why does a closure that only reads
countnot needmut? - Which of the traits
Fn,FnMutandFnOncedoesincimplement?