不能借用不可变的s,因为它也借来可变

时间:2020-10-29 06:53:57

标签: rust immutability mutable

我遇到了不可变的借贷问题。不可变借位发生在“ println!(” {}“,s);”中,但后来我不再使用不可变借位值。

我有:

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

它在抱怨:

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

1 个答案:

答案 0 :(得分:0)

在锈病中,您无法做这些事情。一切都有一个所有者,只能存在于一个地方。

浏览代码:

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.
}

因此,要编写摘要的一件事是在r3变量周围添加一个作用域。

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
}