目前在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 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
结构和枚举也是如此 – 它们也可以部分移动.