W3cubDocs

/Rust

Function std::mem::replace

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.

Examples

A simple example:

use std::mem;

let mut v: Vec<i32> = vec![1, 2];

let old_v = mem::replace(&mut v, vec![3, 4, 5]);
assert_eq!(2, old_v.len());
assert_eq!(3, v.len());

replace allows consumption of a struct field by replacing it with another value. Without replace you can run into issues like these:

This example deliberately fails to compile
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:

use std::mem;

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

© 2010 The Rust Project Developers
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.
https://doc.rust-lang.org/std/mem/fn.replace.html