I came across this reddit comment. This is a "safe" feature of rust I didn't know about.
I was at first confused about the docs for std::mem::replace however. My main confusion was around the "deinitializing" word which made me think that T is _not_ consumed. It _is_ consumed but it is _not dropped_, which is a subtle distinction. I propose here to remove the confusing language.
pub fn replace<T>(dest: &mut T, src: T) -> TReplaces the value at a mutable location with a new one, returning the old value, without deinitializing either one.
Suggested new docs:
pub fn replace<T>(dest: &mut T, src: T) -> TConsumes
srcto replace the value atdestin-place, returning the old value.Neither value is dropped.
Another possible option (I don't like it as much but it is more similar to the previous docs):
pub fn replace<T>(dest: &mut T, src: T) -> TReplaces the value at a mutable location with a new one, returning the old value.
Neither value is dropped.
As a side note, I have not seen the "deinitialized" qualifier in rust before. I don't think it is part of the standard rust lingo which is probably some of my confusion :smile:
Another option, which I think is the best of both worlds:
Moves
srcbehind the mutable referencedest, returning the previous value.Neither value is dropped.
The important points are to mention that src is moved, and to use standard Drop terminology rather than "deinitialized".
I like the third option the most:
Replaces the value at a mutable location with a new one, returning the old value.
Neither value is dropped.
@CAD97 I have to say I like yours the best. Maybe change "Moves src _behind_ the mutable reference" to "Moves src _into_ the mutable reference"? I'm not sure "behind" is standard lingo either :smile:
opened a pr https://github.com/rust-lang/rust/pull/51124
Most helpful comment
Another option, which I think is the best of both worlds:
The important points are to mention that
srcis moved, and to use standardDropterminology rather than "deinitialized".