JoeDoe
JoeDoe

Reputation: 33

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.

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

Upvotes: 3

Views: 282

Answers (2)

Netwave
Netwave

Reputation: 42786

Alternatively to @Smitop answer you can move into a new swaped Data. Notice that you cannot move from a &mut so the signature would have to change too:

impl Data {
    fn proc(self) -> Self {
        Self {
            xs: self.ys, ys: self.xs
        }
    }
}

Playground

Upvotes: 2

loops
loops

Reputation: 5705

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.

Upvotes: 4

Related Questions