[英]How can I use a closure that has mutably captured a variable in a loop that checks the same value?
fn main() {
let mut foo = 1;
let mut func = || foo += 1;
while foo < 5 {
func();
}
}
error[E0503]: cannot use `foo` because it was mutably borrowed
--> src/main.rs:5:11
|
4 | let mut func = || foo += 1;
| -- borrow of `foo` occurs here
5 | while foo < 5 {
| ^^^ use of borrowed `foo`
我知道為什么這行不通,但是我正在尋找一種以某種方式繞過借用檢查器的方法。 有沒有辦法在這里使用閉包? 除了使用函數以外,還有其他好的選擇嗎? 我遇到了必須更改幾個變量的情況。
您有一個選擇是將可變引用傳遞給閉包,而不是通過環境捕獲隱式借用它:
fn main() {
let mut foo = 1;
let func = |foo: &mut i32| *foo += 1;
while foo < 5 {
func(&mut foo);
}
}
不 ,您不能這樣做。 盡管閉包具有可變的借位,但是其他任何人都不能訪問該變量。
代替...
您可以使用Cell
或RefCell
:
use std::cell::Cell;
fn main() {
let foo = Cell::new(1);
let func = || foo.set(foo.get() + 1);
while foo.get() < 5 {
func();
}
}
也可以看看:
您可以將比較烘烤到閉包中:
fn main() {
let mut foo = 1;
let mut func = || {
foo += 1;
foo < 5
};
while func() {}
}
struct Thing(i32);
impl Thing {
fn do_it(&mut self) {
self.0 += 1
}
fn test_it(&self) -> bool {
self.0 < 5
}
}
fn main() {
let mut foo = Thing(1);
while foo.test_it() {
foo.do_it();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.