2017-09-20 6 views
2

私は何度も変更可能な変数の詳細を借りして、エラーなしでコンパイルこのコードを書いたが、The Rust Programming Languageによると、これはコンパイルできませんする必要があります複数の可変借用が同じ有効範囲内で可能なのはなぜですか?

fn main() { 
    let mut s = String::from("hello"); 

    println!("{}", s); 
    test_three(&mut s); 
    println!("{}", s); 
    test_three(&mut s); 
    println!("{}", s); 
} 

fn test_three(st: &mut String) { 
    st.push('f'); 
} 

playground

は、これはバグですか、そこにありますRustの新機能ですか?

答えて

5

ここで何も起こりません。可変ボローが無効になっtest_three関数は(右のそれを呼び出して後で)その作業を終了するたびに:

fn main() { 
    let mut s = String::from("hello"); 

    println!("{}", s); // immutably borrow s and release it 
    test_three(&mut s); // mutably borrow s and release it 
    println!("{}", s); // immutably borrow s and release it 
    test_three(&mut s); // mutably borrow s and release it 
    println!("{}", s); // immutably borrow s and release it 
} 

は、関数は引数を保持していない - それは、それが借りて解放指すStringを変異させます右その後、それはもはや必要ないので:

fn test_three(st: &mut String) { // st is a mutably borrowed String 
    st.push('f'); // the String is mutated 
} // the borrow claimed by st is released 
+0

このようなものが「何度も変更可能な多くを借りることができない」、私は古いさびコンパイラで、数ヶ月前に類似したコードを書いて、私はエラーをコンパイルしました。 しかし、バージョン1.20で動作しています。 – mojtab23

+2

@ mojtab23実際にはこれは新しいものではなく、Rust 1.0以来正常に動作するはずです。 [godbolt's rustc 1.0](https://rust.godbolt.org)との問題なくコンパイルされます。あなたが参照しているコードには、おそらく(一見して微妙であっても)かなりの違いがあります。 – ljedrz

関連する問題