Consider the following code:
struct MyStruct {
not_copyable: NotCopyable
}
struct NotCopyable;
fn main() {
let foo = MyStruct { not_copyable: NotCopyable };
foo.not_copyable;
foo.not_copyable;
// just found out the simpler "foo; foo;" will create the same problem
}
这段代码编译失败,报错信息如下:
src/main.rs:17:5: 17:21 error: use of moved value: `foo.not_copyable` [E0382]
src/main.rs:17 foo.not_copyable;
^~~~~~~~~~~~~~~~
src/main.rs:16:5: 16:21 note: `foo.not_copyable` moved here because it has type `NotCopyable`, which is non-copyable
src/main.rs:16 foo.not_copyable;
^~~~~~~~~~~~~~~~
error: aborting due to previous error
虽然我对所有权系统还不是很熟悉,但我明白为什么你不能创建两个let
绑定到foo.not_copyable
。但在这种情况下没有绑定。那么谁拥有not_copyable
;它被移动到哪里了?
foo.not_copyable
移动了两个值:foo
和foo
的not_copyable
,这正确吗? - musiKkfoo.not_copyable
。如果结构中有两个字段,您可以先移动一个,然后再移动另一个。话虽如此,一旦移动了non_copyable
,整个foo
结构就被有效地移动了。 - DK.foo
被部分移动了。因为如果你在foo.not_copyable
之后尝试评估foo
,错误消息就是这样说的。 - musiKk