【发布时间】:2018-03-07 20:11:26
【问题描述】:
我试图理解为什么下面的代码会失败:
fn main() {
let mut a = 10;
let mut b = 20;
let mut c = 30;
let p = vec![&mut a, &mut b, &mut c]; // works with [&a, &b, &c]
for &x in &p { // works with 'x' instead of of '&x'
println!("{}", x);
}
}
错误信息是:
error[E0507]: cannot move out of borrowed content
--> src/main.rs:7:9
|
7 | for &x in &p {
| ^-
| ||
| |hint: to prevent move, use `ref x` or `ref mut x`
| cannot move out of borrowed content
据我了解,“借用内容”是vec! 对变量a、b、c 的可变引用,但究竟是什么在这里“移动”了?我认为移动发生在for 循环的开头。
我认为有两个可变引用(一个来自vec),但我想我无法正确解构&x,我知道答案就在那里。如果我按照编译器的建议将ref x 放在那里或使用&&mut x,我能够理解它为什么会起作用,但我不理解上述情况。 (即&x)。
【问题讨论】: