2017-04-20 2 views
2

私はRustを試していて、 "借りる"ことを理解する上でいくつかの問題があります。Rustの借り入れを解放する

fn main() { 
    let mut x = 10; 
    let mut a = 6; 
    let mut y = &mut x; 

    *y = 6; 
    y = &mut a; 

    x = 15; 
    println!("{}", x); 
} 

そして、私はエラーを持っている:

error[E0506]: cannot assign to `x` because it is borrowed 
--> <anon>:9:5 
    | 
4 |  let mut y = &mut x; 
    |      - borrow of `x` occurs here 
... 
9 |  x = 15; 
    |  ^^^^^^ assignment to borrowed `x` occurs here 

error[E0502]: cannot borrow `x` as immutable because it is also borrowed as mutable 
    --> <anon>:10:20 
    | 
4 |  let mut y = &mut x; 
    |      - mutable borrow occurs here 
... 
10 |  println!("{}", x); 
    |     ^immutable borrow occurs here 
11 | } 
    | - mutable borrow ends here 

私は "y -borrowing" からxを解放するにはどうすればよいですか?

+1

あなたは[考えて考える](https://doc.rust-lang.org/stable/book/references-and-borrowing.html#thinking-in-scopes)を開始するだけです。 –

答えて

3

現在のところ、これは「非語彙生涯」(NLL)と呼ばれることが多いRust借用チェッカーの制限です。ここで問題となるのは、変数への参照を割り当てるとき(let mut y = &mut x;)、変数のスコープ全体に対して参照が有効でなければならないということです。これは、「xは借用されました」がyのスコープ全体にわたって続くことを意味します。したがって、コンパイラはラインy = &mut a;を気にしません!

これについてのより多くの(技術的)議論を読むことができますhere at the tracking issue

関連する問題