1

I have the following issue: In the get_new_experiences method I want to return a Vec while also emptying it.

struct ExperienceBuffer {
    experiences: Vec<Experience>,
}

impl ExperienceBuffer {
    pub fn new(capacity: usize) -> ExperienceBuffer {
        return ExperienceBuffer {
            experiences: Vec::with_capacity(capacity),
        };
    }
    
    pub fn put_experience(&mut self, exp: Experience) {
        self.experiences.push(exp);
    }

    pub fn get_new_experiences(&mut self) -> Vec<Experience> {
        let mut result = Vec::new();
        swap(&mut self.experiences, &mut result);
        return result;
    }
}

Is this the correct way to do this?

  • 5
    As mentioned in the second answer here, [`std::mem::take`](https://doc.rust-lang.org/std/mem/fn.take.html) is a good fit for what you want, e.g. `pub fn get_new_experiences(&mut self) -> Vec {std::mem::take(&mut self.experiences) }` since `Vec` implements `Default`. – loganfsmyth Jul 06 '21 at 23:55

0 Answers0