ad-si/Rust-Flashcards

Card "What's a workaround we can use to allow multiple mutable references to the same data?"

Closed this issue · 1 comments

Current answer

We can use curly brackets to create a new scope, allowing for multiple mutable references, just not simultaneous ones:

fn main() {
  let mut s: String = String::from("Hello");
  {
    let r1: &mut String = &mut s;
    // r1 goes out of scope here,
  }
  // So we can make a new reference with no problems
  let r2: &mut String = &mut s;
}

Proposal

I think this answer is not correct. In fact thanks to NLL the above code works without curly braces too (https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=6b2144aeb8d82883ec17cb94af60c888).

At first, I would have answered to use a Mutex. So I'm not sure how to update this card.

  1. Remove it
  2. Use an example that does not compile, for instance the one at the end of https://blog.rust-lang.org/2022/08/05/nll-by-default.html, but here the solution is not about adding curly braces
  3. Update the question to point to a Mutex answer

The example in the book (https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html#mutable-references) does fail, because the r1 and r2 are used simultaneously. So the workaround is to not use them at the same time. (You can't exactly fix the example code with that, but it's a workaround after all.)

So I think the answer is OK for the question and I think it's recognizable enough that the code isn't complete and it's implied that you would usually do something with r1 and r2.

Do you agree?