1 回答

TA貢獻1864條經驗 獲得超6個贊
這行:
n.set(n.get() + 1);
被減為
Number::set(&mut n, n.get() + 1);
現在,錯誤消息可能會更加清楚:
error[E0502]: cannot borrow `n` as immutable because it is also borrowed as mutable
--> <anon>:18:25
|
18 | Number::set(&mut n, n.get() + 1);
| - ^ - mutable borrow ends here
| | |
| | immutable borrow occurs here
| mutable borrow occurs here
當Rust從左到右評估參數時,該代碼與此等效:
let arg1 = &mut n;
let arg2 = n.get() + 1;
Number::set(arg1, arg2);
現在應該很明顯出了什么問題。交換前兩行即可解決此問題,但Rust不會進行這種控制流分析。
它最初是作為Bug#6268創建的,現在已集成到RFC 2094(非詞法生存期)中。如果您使用Rust 2018,則會自動啟用NLL,并且您的代碼現在將編譯而不會出現錯誤。
- 1 回答
- 0 關注
- 860 瀏覽
添加回答
舉報