【Rust】HashMap

1. new

2. 所有权

3. get

4. iterator

5. insert

6. or_insert

==============================================================

1. new

let mut scores = HashMap::new();
scores.insert(String::from("Blue"), 10);

2. 所有权

let key: String = String::from("key1");
let value: String = String::from("value2");
let mut scores = HashMap::new();
// 对于像 String 这样拥有所有权的值,其值将被移动而哈希 map 会成为这些值的所有者
scores.insert(key, value);
// println!("{},{}",key,value); // key和value不再有效

3. get

let mut scores = HashMap::new();
scores.insert(String::from("name"), String::from("Tom Smith"));
let k = String::from("name");
let v: Option<&String> = scores.get(&k);
match v {
    Some(x) => println!("{}",x),
    None => println!("none value"),
}

4. iterator

let mut scores = HashMap::new();
scores.insert(String::from("name"), String::from("Tom Smith"));
for (key, value) in &scores {
    println!("{}: {}", key, value);
}

5. insert

let mut scores = HashMap::new();
scores.insert(String::from("name"), String::from("Tom Smith"));
scores.insert(String::from("name"), String::from("Tom Smith 2"));// 使用新值覆盖老值
println!("{:?}", scores);

6. or_insert

let mut scores = HashMap::new();
scores.insert(String::from("name"), String::from("Tom Smith"));
scores.entry(String::from("name")).or_insert(String::from("Tom Smith 2"));// 不存在时才插入,存在返回这个值的可变引用
println!("{:?}", scores);

 

posted @   翠微  阅读(318)  评论(0编辑  收藏  举报
(评论功能已被禁用)
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示