我正在尝试将变量的所有权赋予循环中的函数,并且我有自己的布尔值以确保它仅发生一次,但是编译器告诉我该值是在上一次迭代中移动的。
这里是一个示例:
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);
}
}
}
使用此代码,编译器告诉我:
error[E0382]: use of moved value: `hello`
--> src/main.rs:12:28
|
12 | take_ownership(hello);
| ^^^^^ value moved here in previous iteration of loop
有没有办法告诉编译器“没关系,我会处理的”?我不想使用引用(&
)。
答案 0 :(得分:6)
告诉编译器“可以,我会处理”的通常方法是使用func animateViewIn() {
alertView.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
alertView.center = self.view.center
UIApplication.shared.keyWindow?.addSubview(alertView)
}
。您可以在这里使用unsafe
以及一些深奥的unsafe
魔术,但这将非常脆弱并且难以证明正确。
但是,用ptr
做这件事是安全且容易的:
Option
在原始版本中,let mut a = Some("Hello".to_string());
for _ in 0..5 {
if let Some(hello) = a.take() {
take_ownership(hello);
}
}
和a
之间没有类型级别的关系,因此编译器无法确定hello
仅被移动了一次。 hello
将不变的“这里可能有东西,或者可能消失了”编码为类型,因此编译器可以知道Option
仅在存在要传递给它的东西。
.take()
是一种用take_ownership
代替a
并返回内容(如果有)的方法。因为此方法不消耗None
,所以可以在循环中多次调用它。 Cannot move out of borrowed content when trying to transfer ownership是一个相关问题。