How does assigning to a borrowed variable violate the rules of references?

别来无恙 提交于 2020-05-31 06:31:08

问题


I have this code:

struct Foo<'a> {
    link: &'a i32,
}

fn main() {
    let mut x = 33;
    println!("x:{}", x);
    let ff = Foo { link: &x };
    x = 22;
}

Which generates this compiler error:

error[E0506]: cannot assign to `x` because it is borrowed
 --> src/main.rs:9:5
  |
8 |     let ff = Foo { link: &x };
  |                           - borrow of `x` occurs here
9 |     x = 22;
  |     ^^^^^^ assignment to borrowed `x` occurs here

The Rust book has only two rules:

  1. one or more references (&T) to a resource,
  2. exactly one mutable reference (&mut T).

I have one mutable variable and one immutable link. Why does the compiler give an error?


回答1:


The Rust Programming Language defines the rules of references:

  • At any given time, you can have either one mutable reference or any number of immutable references.
  • References must always be valid.

Reassigning a variable implicitly requires a mutable reference:

fn main() {
    let mut x = 33;
    let link = &x;
    x = 22;
    *(&mut x) = 22; // Basically the same thing
}

Importantly, reassigning a variable mutates the variable, which would cause the value of the immutable reference link to change, which is disallowed.

Note that the initial assignment of the variable does not require the variable to be mutable:

fn main() {
    let x;
    // Some other code
    x = 42;
}


来源:https://stackoverflow.com/questions/46157422/how-does-assigning-to-a-borrowed-variable-violate-the-rules-of-references

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!