0

Folks,

I am writing some code to learn Rust.

I read about the rule that states you can have at most ONE mutable borrow for a variable going on simultaneously in the scope of your code.

Then, while I was writing some reference to myself, I stumbled on this:

    fn main() {
        let mut a = "Is this string immutable?".to_string();
        println!("a: {}\n", a);
    
        let b = &mut a;
        b.push_str(" No, it's not.");
    
        let c = &mut a;
    
        // b.push_str(" Could we append more stuff here?");
    
        println!("c: {}",c);
    }

The weird situation is: this code works as is, even if I declared two mutable borrows.

BUT... If I comment out the second push_str() call, the compiler would start to complain about the second mutable borrow in the c variable declaration.

What am I missing here? Why is it running?

Thanks in advance.

1 Answers1

4

The rule is that you cant have to mutable borrows which are active at the same time.

In your case this is not the case. The borrow b just has to be alive until the line b.push_str(" No, it's not.");. After this you are free to borrow again, because b is never used again. When outcommenting you extend the lifetime of b after your second borrow and you get an error.

The compiler is not always able to recognize this in more complicated situations, so it might fail to compile even if at no point there could be 2 mutable borrows.

Unlikus
  • 1,419
  • 10
  • 24
  • 1
    An other component of this is that some constructs ([most famously `match`](https://fasterthanli.me/articles/a-rust-match-made-in-hell)) will "artificially" extend lifetimes, which can be unexpected. – Masklinn Feb 15 '22 at 11:56