【问题标题】:how to replace member of a structure using this member's method which consume this member itself? [duplicate]如何使用消耗此成员本身的此成员方法替换结构的成员? [复制]
【发布时间】:2019-07-04 07:58:18
【问题描述】:

我有一个枚举,它可能包含一个向量。我为枚举实现了一个方法,它可以生成一个新的枚举,它在以前的枚举中重用相同的向量(我不想复制向量)。生成新的枚举后,我不会再使用以前的枚举,所以我将这个方法实现为fn (self),它将获得枚举的所有权。

然后我把enum放到一个结构体中,我想用我刚刚实现的enum的方法来替换结构体中的enum。但是我收到了这个错误:

error[E0507]: cannot move out of borrowed content
  --> src/lib.rs:22:18
   |
22 |         self.0 = self.0.get_a_new_foo();
   |                  ^^^^^^ cannot move out of borrowed content

有什么方法可以修复我的代码吗?

enum Foo {
    A,
    B(Vec<u32>),
}

impl Foo {
    fn get_a_new_foo(self) -> Foo {
        match self {
            Foo::A => Foo::B(vec![]),
            Foo::B(mut v) => {
                let len = v.len() as u32;
                v.push(len - 1);
                Foo::B(v)
            }
        }
    }
}

struct Bar(Foo);
impl Bar {
    fn replace_foo(&mut self) -> () {
        self.0 = self.0.get_a_new_foo();
    }
}

【问题讨论】:

  • 请始终包含 full 错误消息,因为如您所见,问题不在get_a_new_foo 函数中,而在您的replace_foo 函数中。跨度>

标签: rust lifetime ownership


【解决方案1】:

您可以使用take_mut 优雅地做到这一点:

struct Bar(Foo);
impl Bar {
    fn replace_foo(&mut self) -> () {
        take_mut::take(&mut self.0, |foo| foo.get_a_new_foo());
    }
}

或者,无需额外的依赖项,您也可以这样做:

struct Bar(Foo);
impl Bar {
    fn replace_foo(&mut self) -> () {
        let mut tmp = Foo::A;
        std::mem::swap(&mut tmp, &mut self.0);
        tmp = tmp.get_a_new_foo();
        std::mem::swap(&mut tmp, &mut self.0);
    }
}

但它只有在您可以廉价构建Foo 的一些“占位符”变体时才有效,例如在本例中为Foo::A。

【讨论】:

  • 可以使用replace 代替swap。查看建议的副本
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-11-14
  • 2019-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-25
  • 2011-08-22
相关资源
最近更新 更多