diff options
| author | bors <bors@rust-lang.org> | 2014-04-28 11:32:07 -0700 |
|---|---|---|
| committer | bors <bors@rust-lang.org> | 2014-04-28 11:32:07 -0700 |
| commit | 1f4278d650837bf30e5461fd15c2364b2bb5ceff (patch) | |
| tree | 91a8c94e84ead9143bd0faa1691e94d82ce72026 /src/libstd | |
| parent | 3e284eeb21d8276abecd052b8a72e3146e787e95 (diff) | |
| parent | 1be93e61da4cd63840a0b5318785547a009e8cae (diff) | |
| download | rust-1f4278d650837bf30e5461fd15c2364b2bb5ceff.tar.gz rust-1f4278d650837bf30e5461fd15c2364b2bb5ceff.zip | |
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
Diffstat (limited to 'src/libstd')
| -rw-r--r-- | src/libstd/mem.rs | 32 |
1 files changed, 32 insertions, 0 deletions
diff --git a/src/libstd/mem.rs b/src/libstd/mem.rs index 342e565572b..d216d91b901 100644 --- a/src/libstd/mem.rs +++ b/src/libstd/mem.rs @@ -248,6 +248,38 @@ pub fn swap<T>(x: &mut T, y: &mut T) { /** * Replace the value at a mutable location with a new one, returning the old * value, without deinitialising or copying either one. + * + * This is primarily used for transferring and swapping ownership of a value + * in a mutable location. For example, this function allows consumption of + * one field of a struct by replacing it with another value. The normal approach + * doesn't always work: + * + * ```rust,ignore + * struct Buffer<T> { buf: Vec<T> } + * + * impl<T> Buffer<T> { + * fn get_and_reset(&mut self) -> Vec<T> { + * // error: cannot move out of dereference of `&mut`-pointer + * let buf = self.buf; + * self.buf = Vec::new(); + * buf + * } + * } + * ``` + * + * Note that `T` does not necessarily implement `Clone`, so it can't even + * clone and reset `self.buf`. But `replace` can be used to disassociate + * the original value of `self.buf` from `self`, allowing it to be returned: + * + * ```rust + * # struct Buffer<T> { buf: Vec<T> } + * impl<T> Buffer<T> { + * fn get_and_reset(&mut self) -> Vec<T> { + * use std::mem::replace; + * replace(&mut self.buf, Vec::new()) + * } + * } + * ``` */ #[inline] pub fn replace<T>(dest: &mut T, mut src: T) -> T { |
