Can I move a vector to inside a struct without fully copying it?

Viewed 280

Mind the following code:

enum Store {
    Place { val: Vec<u8> },
}

fn subst(val: Vec<u8>, store: &mut Store) {
    *store = Store::Place { val }
}

If I understand correctly, here, subst will move val to inside store, which causes it to be copied. Is there any way to do so without copying the whole vector? By "copy" I mean a memory copy. My understanding is that, when a value is moved (such as vec when calling subst(vec, ...), it requires a full copy to erase the data from the parent function's stack and allocate on the called function's stack.

1 Answers

This operation only copies the Vec object, i.e. the pointer to its contents (but not the contents themself), capacity and length, so you shouldn't be concerned about the performance:

fn move_vec(v: Vec<usize>) -> Vec<usize> {
    v
}

fn main() {
    let v1 = vec![1, 2, 3];
    println!("{:p}", &v1[1]);

    let v2 = move_vec(v1);
    println!("{:p}", &v2[1]); // the same location as above
}
Related