Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Chapter 2 Closure Example won't compile #27

Closed
andradei opened this issue Mar 27, 2017 · 3 comments
Closed

Chapter 2 Closure Example won't compile #27

andradei opened this issue Mar 27, 2017 · 3 comments

Comments

@andradei
Copy link

andradei commented Mar 27, 2017

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).

@stevedonovan
Copy link
Owner

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 ;)

@andradei
Copy link
Author

andradei commented Mar 27, 2017

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.

@andradei
Copy link
Author

Well, you were fast. I'm closing this unless you object.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants