Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to swap two vectors in a mutable struct

There is the following struct:

struct Data {
    xs: Vec<i32>,
    ys: Vec<i32>
}

At attempt to assign one vector of the struct to the other as follows leads to an error:

impl Data {
    fn proc(&mut self) {
        self.xs = self.ys;
    }
}

The error is move occurs because self.ys has type Vec<i32>, which does not implement the Copy trait.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The struct is borrowed as mutable, why it is not possible to move from self.ys there?

>Solution :

Use std::mem::swap to swap the values in-place:

impl Data {
    fn proc(&mut self) {
        std::mem::swap(&mut self.xs, &mut self.ys);
    }
}

(playground)

self.xs = self.ys doesn’t work because Vec doesn’t implement Copy: you’d have to .clone() ys.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading