目前在 Rust master(0.10-pre)中,当您移动一个唯一向量的一个元素并尝试移动另一个元素时,编译器会报错:
let x = ~[~1, ~2, ~3];
let z0 = x[0];
let z1 = x[1]; // error: use of partially moved value: `x`
此错误消息与移动整个向量时的错误消息有些不同:
let y = ~[~1, ~2, ~3];
let y1 = y;
let y2 = y; // error: use of moved value `y`
为什么不同的信息?如果 x
在第一个例子中只是“部分移动”,有没有办法“部分移动” x
的不同部分?如果不是,为什么不直接说 x
被移动了呢?
最佳答案
If x is only "partially moved" in the first example, is there any way to "partially move" different parts of x?
是的,有,但只有当你同时移动这些部分时:
let x = ~[~1, ~2, ~3];
match x {
[x1, x2, x3] => println!("{} {} {}", *x1, *x2, *x3),
_ => unreachable!()
}
可以很容易地观察到 xN
确实被移出了,因为如果您在匹配后添加额外的行:
println!("{:?}", x);
编译器会抛出一个错误:
main3.rs:16:22: 16:23 error: use of partially moved value: `x`
main3.rs:16 println!("{:?}", x);
^
note: in expansion of format_args!
<std-macros>:195:27: 195:81 note: expansion site
<std-macros>:194:5: 196:6 note: in expansion of println!
main3.rs:16:5: 16:25 note: expansion site
main3.rs:13:10: 13:12 note: `(*x)[]` moved here because it has type `~int`, which is moved by default (use `ref` to override)
main3.rs:13 [x1, x2, x3] => println!("{} {} {}", *x1, *x2, *x3),
^~
error: aborting due to previous error
结构和枚举也是如此——它们也可以部分移动。
关于rust - Rust 中部分移动的值和移动的值之间有什么区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21367197/