有没有办法告诉编译器我在循环中管理变量的所有权?

Mic*_* B. 1 loops ownership rust

我试图将变量的所有权赋予循环中的函数,并且我有自己的布尔值以确保它只发生一次,但是编译器告诉我在前一次迭代中移动了值.

这是一个例子:

fn take_ownership(a: String) {
    println!("{}", a);
}

fn main() {
    let mut a = true;
    let hello = "Hello".to_string();

    for _ in 0..5 {
        if a {
            a = false;
            take_ownership(hello);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

使用此代码,编译器告诉我:

error[E0382]: use of moved value: `hello`
  --> src/main.rs:12:28
   |
12 |             take_ownership(hello);
   |                            ^^^^^ value moved here in previous iteration of loop
Run Code Online (Sandbox Code Playgroud)

有没有办法告诉编译器"没关系,我会处理它"?我不想使用references(&).

tre*_*tcl 6

通常的方式告诉编译器"没关系,我会处理它"是使用unsafe.您可以使用unsafe这里的一些深沿着ptr魔法,但是这将是非常脆,难以证明是正确的.

但是,这是一个安全而简单的事情Option:

let mut a = Some("Hello".to_string());

for _ in 0..5 {
    if let Some(hello) = a.take() {
        take_ownership(hello);
    }
}
Run Code Online (Sandbox Code Playgroud)

在原文中,a和之间没有类型级关系hello,因此编译器不能确定hello只移动一次.Option编码不变量"这里可能有一个东西,或者它可能已经消失"进入类型,因此编译器可以知道take_ownership只有在有东西传递给它时才会调用它.

.take()是替换的方法aNone,返回的内容(如果有的话).因为这种方法不消耗Option,所以在循环中多次调用它是很好的.尝试转移所有权时无法摆脱借来的内容是一个相关的问题.