Chapter 2 Closure Example won't compile
Closed this issue · 3 comments
Thank you for this project. Has helped me a ton!
File
2-structs-enums-lifetimes.md
Example
let mut answer = 42;
let set = |v| answer = v;
//let get = || answer;
set(58);
assert_eq!(answer, 58);
Won't compile. Compiler yells set
must be mutable, then it complains about the assertion because answer
is currently mutably borrowed by the closure.
One Solution
let mut answer = 42;
{
let mut set = |v| answer = v;
//let get = || answer;
set(58);
}
assert_eq!(answer, 58);
Using the extra scope might throw beginners off a little... But at least they'll know there is more to closures (lifetimes and scopes).
I agree, and actually decided that was the best way even before I read all the way. (I get embarrassed about compile failures in published work and fix them quickly). Mutable borrowing is a strict business! Thanks for the keen eye. The general solution I have is that I must always use rustc
as my first proof-reader ;)
rustc
is the best proof reader for Rust code there is :)
And let mut set = // closure...
could be a great point to bring back later when you explain how Fn
, FnMut
, and FnOnce
work (maybe a Closures in Depth section).
Thanks again for this great material.
Well, you were fast. I'm closing this unless you object.