remove_entry Recovers The Owned Key

Take full ownership of removed map data with HashMap::remove_entry, which returns the key and value instead of dropping the key.

RustData Integrity

Code

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

fn main() {
    let mut caps: HashMap<String, u32> = HashMap::from([
        ("TLS1_2".to_string(), 12),
        ("tls1_3".to_string(), 13),
    ]);

    // remove_entry 拿回拥有所有权的 (K, V):原始键被一并移出
    if let Some((key, ver)) = caps.remove_entry("TLS1_2") {
        println!("removed {key} with value {ver}");
    }

    // remove 只返回值;键本身被丢弃
    let ver = caps.remove("tls1_3");
    println!("remove returned value only: {ver:?}");
    println!("map is empty: {}", caps.is_empty());

    // 缺失键:两种方法都返回 None
    assert!(caps.remove_entry("missing").is_none());
    println!("missing key: None");
}

What the code does

remove_entry Recovers The Owned Key keeps everything in the function main.

Caveats

  • No third-party packages — the runtime supplies every API used here.

Using it

Entry signature: fn main()

Output lines are prefixed (removed, remove returned value only:, map is empty:), making each step’s effect easy to spot.

Key statements

if let Some((key, ver)) = caps.remove_entry("TLS1_2") {
println!("removed {key} with value {ver}");
}

Interactive Tools for This Topic

FAQ

What does remove_entry Recovers The Owned Key print when run?
Invoke the file as-is — the `removed`, `remove returned value only:`, `map is empty:` prefixes identify which step printed each line.