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


i have struct

struct test {     list: vec<u64> } 

and method in vector , erase list field empty vec

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

it there approach doing it? autoreinit field on moving value, example:

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

here solution, can test on rust playground (sadly share button doesn't work 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 need run mem::replace(docs) on mutable value , replace value moved in place. in case our destination self.list , value replacing blank vec.

things note:

  • field self.list of test, needs taken &mut self.list.
  • previous change implies self should mutable well.
  • second parameter of replace moved. means won't available further after call. means, either pass vec constructor (e.g. vec::new()) or clone of value that's replacing.

Comments

Popular posts from this blog

javascript - AngularJS custom datepicker directive -

javascript - jQuery date picker - Disable dates after the selection from the first date picker -