Why can't a mutable variable be used when a mutable reference to that variable can?

Viewed 1026

I have a mutable string variable, and an immutable variable bound to a mutable reference to the mutable string variable.

let mut string = String::from("test");
let variable: &mut String = &mut string;
variable.push_str(" test");
string.push_str(" test");

This fails:

error[E0499]: cannot borrow `string` as mutable more than once at a time
 --> src/main.rs:5:5
  |
3 |     let variable: &mut String = &mut string;
  |                                      ------ first mutable borrow occurs here
4 |     variable.push_str(" test");
5 |     string.push_str(" test");
  |     ^^^^^^ second mutable borrow occurs here
6 | }
  | - first borrow ends here
  1. Without the second variable being mutable, why am I able to call push_str?
  2. Why am I able to call push_str on the second variable and not on the first?
2 Answers
Related