# Function std::mem::replace 1.0.0 [−] [src]

    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 or copying either one.

This is primarily used for transferring and swapping ownership of a value in a mutable location.

# Examples

A simple example:

fn main() { use std::mem; let mut v: Vec<i32> = Vec::new(); mem::replace(&mut v, Vec::new()); }

    use std::mem;

    let mut v: Vec<i32> = Vec::new();

    mem::replace(&mut v, Vec::new());

This function allows consumption of one field of a struct by replacing it with another value. The normal approach doesn't always work:

fn main() { 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 } } }

    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:

fn main() { #![allow(dead_code)] use std::mem; struct Buffer<T> { buf: Vec<T> } impl<T> Buffer<T> { fn get_and_reset(&mut self) -> Vec<T> { mem::replace(&mut self.buf, Vec::new()) } } }

    use std::mem;
    impl<T> Buffer<T> {
        fn get_and_reset(&mut self) -> Vec<T> {
            mem::replace(&mut self.buf, Vec::new())
        }
    }

# Help

## Keyboard Shortcuts

?
  Show this help dialog
S
  Focus the search field
⇤
  Move up in search results
⇥
  Move down in search results
⏎
  Go to active search result
+
  Collapse/expand all sections

## Search Tricks

Prefix searches with a type followed by a colon (e.g. `fn:`) to restrict the search to a given type.

Accepted types are: `fn`, `mod`, `struct`, `enum`, `trait`, `type`, `macro`, and `const`.

Search functions by type signature (e.g. `vec -> usize` or `* -> vec`)