std-method

Rust Cell::replace

Replace the stored value and receive the old value by ownership. This is useful for changing an owned string without borrowing its internal buffer. Unlike set, replace returns the previous payload. Expected output (not executed): queued -> sent Why: Both strings are owned at their respective destinations. Common mistake: Calling get on Cell<String>.

Formal Syntax & Structure

rust syntaxrust
cell.replace(value) -> T

Working Example

Example Snippetrust
use std::cell::Cell;fn main() {    let status = Cell::new(String::from("queued"));    let previous = status.replace(String::from("sent"));    println!("{previous} -> {}", status.into_inner());}
Rust Reference