Insert Replaces And Returns Old Value

HashMap::insert replaces the stored value and returns the old one moved out, so replacing is observable while entry keeps what is already there.

RustData Integrity

Code

rustsnippet
19 lines
use std::collections::HashMap;

fn main() {
    let mut versions: HashMap<&str, String> = HashMap::new();
    versions.insert("web", String::from("v1"));

    // insert replaces the stored value and moves the old value back out by ownership
    let previous = versions.insert("web", String::from("v2"));
    println!("previous: {previous:?}");
    println!("current: {}", versions["web"]);

    // a new key returns None: nothing was stored under it before
    let fresh = versions.insert("api", String::from("v1"));
    println!("fresh: {fresh:?}");

    // entry().or_insert keeps the existing value without replacing it
    versions.entry("web").or_insert_with(|| String::from("v0"));
    println!("after entry: {}", versions["web"]);
}

Inside the snippet

The snippet is organized around the function main.

Watch out for

  • The project needs no additions before running it.

Using it

The main signature is written as fn main()

The file’s steps are announced right in the output: previous:, current:, fresh:.

Statements that do the lifting

versions.entry("web").or_insert_with(|| String::from("v0"));
let previous = versions.insert("web", String::from("v2"));
let mut versions: HashMap<&str, String> = HashMap::new();

Interactive Tools for This Topic

FAQ

What does Insert Replaces And Returns Old Value print when run?
Execute the whole file; each printed line is prefixed with a label like `previous:`, `current:`, `fresh:`.