gpt4 book ai didi

rust - 如何移出作为选项的结构字段?

转载 作者:行者123 更新时间:2023-11-29 07:47:26 25 4
gpt4 key购买 nike

我想收集对结构的更改并一次性全部应用。基本大纲如下所示:

enum SomeEnum {
Foo,
Bar,
}

struct SomeStruct {
attrib: SomeEnum,
next_attrib: Option<SomeEnum>,
}

impl SomeStruct {
pub fn apply_changes(&mut self) {
if let Some(se) = self.next_attrib {
self.attrib = se;
}
self.next_attrib = None;
}
}

这会产生以下编译器错误:

error[E0507]: cannot move out of borrowed content
--> src/lib.rs:13:27
|
13 | if let Some(se) = self.next_attrib {
| -- ^^^^ cannot move out of borrowed content
| |
| hint: to prevent move, use `ref se` or `ref mut se`

我找到了 Get an enum field from a struct: cannot move out of borrowed content并将 #[derive(Clone, Copy)] 添加到我的枚举定义中。

这可能有效,但我对(隐含地)使用复制感到不舒服,因为这通常也可能发生在较大的数据类型上。

实际所有者永远不会移出结构。

是否有另一种方法可以完成此操作,而不会将Copy/Clone 特征暴露给枚举的所有用户?

最佳答案

从本质上讲,如果 self.attrib 仍由 self.next_atrrib 拥有,则不能将值分配给它。这意味着您需要从 self.next_attrib 中删除值,然后将所有权授予 self.attrib

执行此操作的一种方法是手动替换值。例如,您可以使用 std::mem::replace将值替换为 None 并将当前值的所有权作为 next_attrib。然后你可以取值,如果它是Some(_),你可以把它的内容放在self.attrib中。:

impl SomeStruct {
pub fn apply_changes(&mut self) {
let next_attrib = std::mem::replace(&mut self.next_attrib, None);
if let Some(se) = next_attrib {
self.attrib = se;
}
}
}

由于这是一个相对常见的模式,但是,Option 上有一个实用函数来处理您想要拥有 Option 内容的情况> 并将 Option 设置为 NoneOption::take方法就是你想要的。

impl SomeStruct {
pub fn apply_changes(&mut self) {
if let Some(se) = self.next_attrib.take() {
self.attrib = se;
}
}
}

另见:

关于rust - 如何移出作为选项的结构字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52031002/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com