JIoJIaJIu
JIoJIaJIu

Reputation: 155

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

I have a struct

struct Test {
    list: Vec<u64>
}

and method in which I would like to get vector and erase list field to empty Vec

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

It there another approach for doing it? Something like autoreinit field on moving value, for example:

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

Upvotes: 1

Views: 534

Answers (2)

Daniel Fath
Daniel Fath

Reputation: 18109

Here is the solution, you can test on Rust playground (sadly share button doesn't work for me 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);
}

You just need to run mem::replace(docs) on a mutable value and replace it with a value that will be moved in its place. In this case our destination is self.list and value we are replacing it is a blank Vec.

Things to note:

  • Field self.list of Test, needs to be taken as &mut self.list.
  • Previous change implies that self should be mutable as well.
  • Second parameter of replace is moved. That means it won't be available for further after this call. What this usually means, you either pass it a Vec constructor (e.g. Vec::new()) or clone of value that's replacing.

Upvotes: 2

JIoJIaJIu
JIoJIaJIu

Reputation: 155

From #rust IRC

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

Upvotes: -1

Related Questions