3

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.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
MaiaVictor
  • 51,090
  • 44
  • 144
  • 286
  • 1
    Related: [Can Rust optimise away the bit-wise copy during move of an object someday?](https://stackoverflow.com/questions/38571270/can-rust-optimise-away-the-bit-wise-copy-during-move-of-an-object-someday). – ljedrz Sep 19 '18 at 15:18

1 Answers1

6

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
}
ljedrz
  • 20,316
  • 4
  • 69
  • 97
  • Ah, surely. So, just to confirm: any structure that has boxes inside, once moved, only copies the header (the constructor and fields of the enum); the boxed data itself isn't moved at all since it is just a pointer, and the enum owns the area it points to. Correct? – MaiaVictor Sep 19 '18 at 15:22
  • 3
    @MaiaVictor Yes this is why mutex use box. – Stargateur Sep 19 '18 at 15:30