I have a piece of sample code here
let mut s1: String = String :: from("Hello 2");
let s2 = &mut s1;
println!("This is s2: {}", s2);
s1 = s1 + "World";
//println!("This is s1 : {} and s2: {}",s1,s2);
Please note that I have commented out the println!()
statement. From my understanding of rust ownership and borrowing rules, rust does not permit more than one mutable reference to a mutable object at a time. Since s2 has borrowed mutably from s1, I understand that the compiler must throw an error. Yet this is what I get:
warning: value assigned to `s1` is never read
--> src/main.rs:5:5
|
5 | s1 = s1 + "World";
| ^^
|
= note: #[warn(unused_assignments)] on by default
= help: maybe it is overwritten before being read?
Finished dev [unoptimized + debuginfo] target(s) in 0.55s
When I uncomment the println
line, I immediately get three errors. The error messages are as follows:
error[E0506]: cannot assign to `s1` because it is borrowed
--> src/main.rs:5:5
|
3 | let s2 = &mut s1;
| ------- borrow of `s1` occurs here
4 | println!("This is s2: {}", s2);
5 | s1 = s1 + "World";
| ^^ assignment to borrowed `s1` occurs here
6 | println!("This is s1 : {}, s2 : {}", s1, s2);
| -- borrow later used here
error[E0505]: cannot move out of `s1` because it is borrowed
--> src/main.rs:5:11
|
3 | let s2 = &mut s1;
| ------- borrow of `s1` occurs here
4 | println!("This is s2: {}", s2);
5 | s1 = s1 + "World";
| ^^ move out of `s1` occurs here
6 | println!("This is s1 : {}, s2 : {}", s1, s2);
| -- borrow later used here
error[E0502]: cannot borrow `s1` as immutable because it is also borrowed as mutable
--> src/main.rs:6:42
|
3 | let s2 = &mut s1;
| ------- mutable borrow occurs here
...
6 | println!("This is s1 : {}, s2 : {}", s1, s2);
| ^^ -- mutable borrow later used here
| |
| immutable borrow occurs here
error: aborting due to 3 previous errors
What is even more confusing is that no error is thrown and cargo builds without a hitch if I only println! s1
, instead of both s1
and s2
at the end. The error remains if I only print s2
.
From my understanding of rust, shouldn't there be an error at s1 = s1 + "World"
regardless of what I print after this assignment, since s2
has already mutably borrowed s1
?