顺便说一下,你已经写过的作品。这转让了
a.v
到
b
使无效
a
(旧变量不再存在)。这意味着我们不需要用有效的数据替换取出的数据。这是拥有所有权相对于可变访问的好处之一。
let a = A {
v: VeryLargeStructure {/* ... */},
};
let b = a.v;
// Now `b` has ownership of what was once `a.v`.
// `a` no longer exists as a single entity,
// but you could extract other fields too if you wish.
// E.g. `let c = a.w` if `w` is some other field of `a`.
在上下文中,
struct VeryLargeStructure {
// many tens of fields here
}
struct A {
v: VeryLargeStructure,
}
fn main() {
let a = A {
v: VeryLargeStructure {/* ... */},
};
let b = a.v;
}
(playground)
有点脱色的版本是
destructuring
. 它可以方便地同时提取多个字段。不过,就一个领域而言,
let b = a.v;
可能是首选,因为它更简单、更清晰。
struct VeryLargeStructure {
// many tens of fields here
}
struct A {
v: VeryLargeStructure,
}
fn main() {
let a = A {
v: VeryLargeStructure {/* ... */},
};
let A { v: b } = a;
}
(playground)
注意,如果
A
工具
Drop
,它必须保留所有油田的所有权。这就意味着你不能不更换就搬出去。替换数据(例如
mem::replace
)不过,很好。