std-method

HashMap::insert

Store an owned key and value. For an equivalent existing key, replace the value and return the old value; the stored key itself is retained. For a new key, return None. Expected stdout (not executed): None Some(3) 1 5 Common mistake: Expecting duplicate keys to create multiple values.

Formal Syntax & Structure

rust syntaxrust
pub fn insert(&mut self, k: K, v: V) -> Option<V>

Working Example

Example Snippetrust
fn main() {    use std::collections::HashMap;    let mut scores = HashMap::new();    println!("{:?}", scores.insert("team", 3));    println!("{:?}", scores.insert("team", 5));    println!("{} {}", scores.len(), scores["team"]);}
Rust Reference