Skip to content

Commit 1f4278d

Browse files
committedApr 28, 2014
auto merge of #13797 : lifthrasiir/rust/std-mem-replace-doc, r=alexcrichton
Inspired by @steveklabnik's [comment](http://www.reddit.com/r/rust/comments/240p9s/eli5_stdmemreplace/ch2gxw8), this PR adds the practical use cases to the documentation of `std::mem::replace`. Caveat: We need a `compile-fail` equivalent for doctest. :p
2 parents 3e284ee + 1be93e6 commit 1f4278d

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
 

‎src/libstd/mem.rs

+32
Original file line numberDiff line numberDiff line change
@@ -248,6 +248,38 @@ pub fn swap<T>(x: &mut T, y: &mut T) {
248248
/**
249249
* Replace the value at a mutable location with a new one, returning the old
250250
* value, without deinitialising or copying either one.
251+
*
252+
* This is primarily used for transferring and swapping ownership of a value
253+
* in a mutable location. For example, this function allows consumption of
254+
* one field of a struct by replacing it with another value. The normal approach
255+
* doesn't always work:
256+
*
257+
* ```rust,ignore
258+
* struct Buffer<T> { buf: Vec<T> }
259+
*
260+
* impl<T> Buffer<T> {
261+
* fn get_and_reset(&mut self) -> Vec<T> {
262+
* // error: cannot move out of dereference of `&mut`-pointer
263+
* let buf = self.buf;
264+
* self.buf = Vec::new();
265+
* buf
266+
* }
267+
* }
268+
* ```
269+
*
270+
* Note that `T` does not necessarily implement `Clone`, so it can't even
271+
* clone and reset `self.buf`. But `replace` can be used to disassociate
272+
* the original value of `self.buf` from `self`, allowing it to be returned:
273+
*
274+
* ```rust
275+
* # struct Buffer<T> { buf: Vec<T> }
276+
* impl<T> Buffer<T> {
277+
* fn get_and_reset(&mut self) -> Vec<T> {
278+
* use std::mem::replace;
279+
* replace(&mut self.buf, Vec::new())
280+
* }
281+
* }
282+
* ```
251283
*/
252284
#[inline]
253285
pub fn replace<T>(dest: &mut T, mut src: T) -> T {

0 commit comments

Comments
 (0)