2

While reading Steve Donovan's article Why Rust Closures are (Somewhat) Hard I stumbled upon this code snippet:

let mut x = 1.0;
let mut change_x = || x = 2.0;
change_x();
println!("{}", x);

Steve claims that the code should not compile because of this error:

previous borrow occurs due to use of x in closure

But when I run the code in the Rust Playground, the code works fine. It outputs "2".

I suppose that is because the closure change_x borrows the variable x mutably from the enclosing environment, but ...

  1. Why does the immutable borrow in the println! macro work? x is mutably borrowed in the change_x closure defined above. Steve seems to suggest that this should be an error. Has the compiler been modified to handle this situation differently since the article was published?
  2. The code doesn't compile when I remove the mut marker from change_x. Why?

Side note: the compiler version used by the Playground app is 1.48.0 at the time of posting this question.

Paul Razvan Berg
  • 16,949
  • 9
  • 76
  • 114
  • It's hard to answer multiple questions made in one post. Please separate them into multiple questions so that we can help you better and so that your questions will help others in the future that have one of the same questions as you! – Shepmaster Dec 04 '20 at 17:43
  • 2
    For context, non-lexical lifetimes came with Rust 2018 edition (version 1.31) and this article was probably written with version 1.28 – kmdreko Dec 04 '20 at 18:58
  • Will do, @Shepmaster. Sorry for the trouble and thanks for the tip. – Paul Razvan Berg Dec 04 '20 at 20:02
  • And thanks @kmdreko, yeah Steve used Rust 1.28.0 – Paul Razvan Berg Dec 04 '20 at 20:02

0 Answers0