Rust: improve docs for std::mem::replace

Created on 11 May 2018  路  4Comments  路  Source: rust-lang/rust

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.

Current docs

pub fn replace<T>(dest: &mut T, src: T) -> T

Replaces 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) -> T

Consumes src to replace the value at dest in-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) -> T

Replaces 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:

T-doc

Most helpful comment

Another option, which I think is the best of both worlds:

Moves src behind the mutable reference dest, 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".

All 4 comments

Another option, which I think is the best of both worlds:

Moves src behind the mutable reference dest, 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:

Was this page helpful?
0 / 5 - 0 ratings