rust-lang / nomicon

The Dark Arts of Advanced and Unsafe Rust Programming
https://doc.rust-lang.org/nomicon/
Apache License 2.0
1.74k stars 256 forks source link

Does the use of "consume" imply taking ownerhsip? #406

Closed aryzing closed 1 year ago

aryzing commented 1 year ago

The nomicon states that split_at_mut will consume its value. Does this mean it takes ownership of the value? If so, does it really take ownership?

jonboh commented 1 year ago

From the signature in https://doc.rust-lang.org/std/primitive.slice.html#method.split_at_mut, I wouldn't say that it takes ownership of the value, it consumes the slice which is a (mutable) reference and spits two mutable references. But it doesn't take ownership over the pointed to value.

You can experiment with modified verison of the code snippet that appears in the reference:

let mut v = [1, 0, 3, 0, 5, 6];
let (left, right) = v.split_at_mut(2);
assert_eq!(left, [1, 0]);
assert_eq!(right, [3, 0, 5, 6]);
left[1] = 2;
v[2] = 2; // ERROR! This would imply that you can refer to the values in the slice from two different mutable references
right[1] = 4;

So once, you have left and right as mutable references the mutable reference v is no longer usable.

aryzing commented 1 year ago

Thanks for clarifying.