Reputation: 155
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
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:
self.list
of Test, needs to be taken as &mut self.list
. self
should be mutable as well.Vec::new()
) or clone of value that's replacing.Upvotes: 2
Reputation: 155
From #rust IRC
< theme> jiojiajiu, http://doc.rust-lang.org/nightly/std/mem/fn.replace.html
Upvotes: -1