2017-09-11 68 views
0

我有這樣的代碼:如何分配給借用變量違反引用規則?

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

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

生成此編譯器錯誤:

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 

鏽病本書只有兩個規則:

  1. 一個或多個引用(&T)到資源,
  2. 恰好一個可變參考(&mut T)。

我有一個可變變量和一個不可變鏈接。爲什麼編譯器會提供一個錯誤?

回答

3

The Rust Programming Language, 2nd edition定義the rules of references

  1. At any given time, you can have either but not both of:
    • One mutable reference.
    • Any number of immutable references.
  2. References must always be valid.

賦值給一個變量隱含地需要一個可變的引用:

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

重要的是,分配給一個變量變異變量,這將導致的值不可變參考link更改,這是不允許的。

+1

可能值得注意的是:這兩個規則不是通過「和」連接的,它們通過「或」連接。你只能有一個或另一個,而不是兩個。 –