-1

I'm having trouble with immutable borrow problem. immutable borrow occurs in "println!("{} ", s); " , but later I don't use the immutable borrow value any more.

I have:

fn main() {
    let mut s = String::from("hello");
    let r3 = &mut s;
    println!("{} ", s);
    *r3 = String::from("hello world");
}

And it's complaining:

error[E0502]: cannot borrow `s` as immutable because it is also borrowed as mutable
  --> src/main.rs:31:21
   |
30 |     let r3 = &mut s;
   |              ------ mutable borrow occurs here
31 |     println!("{} ", s);
   |                     ^ immutable borrow occurs here
32 |     *r3 = String::from("hello world");
   |     --- mutable borrow later used here

yhj050806
  • 19
  • 1
  • 2
    The problem isn't whether you reuse the _immutable_ borrow later, the problem is that you have a _mutable_ borrow before the immutable one, and that you use that _mutable_ borrow after. Move the `let r3 = &mut s;` line after the `println`. – Jmb Oct 29 '20 at 07:27

1 Answers1

0

In rust you can't do such things. Everything has an owner and can only exist in one place.

Go through the code:

fn main() {
    let mut s = String::from("hello"); // the String is created
    let r3 = &mut s; // you store are reference in the `r3` variable.
        /// This is almost the same as deleting s (in this scope)
    println!("{} ", s); // this would only work if r3 is out of scope again.
    *r3 = String::from("hello world"); // I don't completely understand this line.
}

So one thing to make your snippet compile would be to add a scope around the r3 variable.

fn main() {
    let mut s = String::from("hello"); // the String is created
    {
        let r3 = &mut s; // `r3` is only valid(in scope) and `s` is moved (invalid) between the braces.
    }
    // now s is valid again. As the `&mut r3` reference is out of scope meaning deleted.
    println!("{} ", s);
    // a new completely unrelated `r3` is created
    let r3 = String::from("hello world"); // readonly r3
}
enaut
  • 431
  • 4
  • 15