File tree Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Original file line number Diff line number Diff 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]
253285pub fn replace < T > ( dest : & mut T , mut src : T ) -> T {
You can’t perform that action at this time.
0 commit comments