Clone Ends The Borrow Early

Turn a map lookup into an owned value with cloned so the borrow ends immediately, letting later inserts into the same HashMap borrow-check cleanly.

RustData Integrity

Code

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

fn main() {
    let mut roles: HashMap<String, String> = HashMap::new();
    roles.insert("ada".to_string(), "admin".to_string());
    roles.insert("bob".to_string(), "viewer".to_string());

    // cloned() 在读取的瞬间把 &String 变成 owned String,借用就此结束
    let role = roles.get("ada").cloned().unwrap_or_default();

    // 没有悬着的借用,同一个 map 现在可以安全地修改
    roles.insert("ada".to_string(), "owner".to_string());

    println!("role was: {role}");
    println!("role now: {:?}", roles.get("ada"));
}

Line-by-line reading

Structurally, expect the function main and nothing else.

Points of care

  • It runs on toolchain defaults — nothing added on top.

Using it

The signature that matters: fn main()

The run prints role was:, role now: — each prefix names the step that produced it.

Key statements

let role = roles.get("ada").cloned().unwrap_or_default();

Interactive Tools for This Topic

FAQ

What does Clone Ends The Borrow Early print when run?
No setup needed: run the file and look for labeled lines like `role was:`, `role now:` in the output.