nha*_*ham 5 rust rust-obsolete
目前在 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`
Run Code Online (Sandbox Code Playgroud)
此错误消息与移动整个向量的错误消息有些不同:
let y = ~[~1, ~2, ~3];
let y1 = y;
let y2 = y; // error: use of moved value `y`
Run Code Online (Sandbox Code Playgroud)
为什么会有不同的消息?如果x在第一个示例中仅“部分移动”,是否有任何方法可以“部分移动” 的不同部分x?如果不是,为什么不直接说x感动呢?
如果在第一个示例中 x 仅“部分移动”,是否有任何方法可以“部分移动”x 的不同部分?
是的,有,但只有当你同时移动这些部分时:
let x = ~[~1, ~2, ~3];
match x {
[x1, x2, x3] => println!("{} {} {}", *x1, *x2, *x3),
_ => unreachable!()
}
Run Code Online (Sandbox Code Playgroud)
可以很容易地观察到xNs 确实被移出了,因为如果您在匹配后添加额外的行:
println!("{:?}", x);
Run Code Online (Sandbox Code Playgroud)
编译器会抛出错误:
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
Run Code Online (Sandbox Code Playgroud)
对于结构和枚举来说也是如此——它们也可以部分移动。
| 归档时间: |
|
| 查看次数: |
724 次 |
| 最近记录: |