移动结构时如何自动清除结构中的属性?

How do I automatically clear an attribute in a struct when it is moved?

我有一个结构

struct Test {
    list: Vec<u64>
}

以及我希望获取向量并将列表字段清空 Vec 的方法

fn get_list(&self) -> Vec<u64> {
    let list = Vec::new();
    for item in self.list.drain() {
        list.push(item);
    }
    list
}

还有其他方法吗?类似于移动值的 autoreinit 字段,例如:

fn get_list(&self) -> ???<Vec<u64>> {
    self.list
}

来自#rust IRC

<主题>jiojiajiu,http://doc.rust-lang.org/nightly/std/mem/fn.replace.html

这是解决方案,您可以在 Rust 操场上进行测试(很遗憾,分享按钮对我的 atm 不起作用)。

use std::mem;

#[derive(Debug)]
struct Test {
   list: Vec<u64>
}

impl Test {

    fn get_list(&mut self) -> Vec<u64> {
       let repl = mem::replace(&mut self.list, Vec::new());
       repl
    }

}

fn main() {
    let mut r = Test {
       list : vec![1,2,3]
    };
    print!("r : {:?} ", r);
    print!("replace : {:?} ", r.get_list());
    print!("r : {:?} ", r);
}

您只需要 运行 mem::replace(docs) 一个可变值并将其替换为将在其位置移动的值。在这种情况下,我们的目的地是 self.list,我们要替换它的值是空白 Vec

注意事项:

  • 测试字段self.list,需取&mut self.list
  • 之前的更改意味着 self 也应该是可变的。
  • replace 的第二个参数被移动。这意味着在这次通话之后它将不再可用。这通常意味着,您要么传递给它一个 Vec 构造函数(例如 Vec::new()),要么传递一个正在替换的值的克隆。