Why are immutable borrows ok after mutable borrows in closures?

Viewed 51

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.

0 Answers
Related