走进 Rust:HashMap 集合
Rust 大约 909 字新建
通过宏新建一个HashMap
对象。
let teams = vec![String::from("Blue"), String::from("Yellow")];
let initial_scores = vec![10, 50];
通过构造函数新建一个HashMap
对象。
let mut scores = HashMap::new();
scores.insert(String::from("Blue"), 10);
scores.insert(String::from("Yellow"), 50);
for (key, value) in &scores {
println!("{}: {}", key, value);
}
更新
覆盖
let mut scores = HashMap::new();
scores.insert(String::from("Blue"), 10);
scores.insert(String::from("Blue"), 25);
println!("{:?}", scores);
只在键没有对应值时插入
let mut scores = HashMap::new();
scores.insert(String::from("Blue"), 10);
scores.entry(String::from("Yellow")).or_insert(50);
scores.entry(String::from("Blue")).or_insert(50);
println!("{:?}", scores);
根据旧值更新一个值
let text = "hello world wonderful world";
let mut map = HashMap::new();
for word in text.split_whitespace() {
let count = map.entry(word).or_insert(0);
*count += 1;
}
println!("{:?}", map);
阅读 3374 · 发布于 2020-07-16
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb扫描下方二维码关注公众号和小程序↓↓↓

昵称:
随便看看
换一批
-
Java 使用 wait 等待会使 synchronized 升级为重量级锁阅读 1978
-
走进 Spring Boot 第一步之 Java Properties 类阅读 2512
-
Docker 部署 Alpine Linux阅读 623
-
使用 logrotate 处理日志阅读 3284
-
Android ListView 条目上有 CheckBox 抢焦点的处理办法阅读 2136
-
软考-系统架构设计师:信息系统开发方法阅读 1485
-
Linux grep/zgrep 提示 Binary file matches阅读 3464
-
Spring Boot 使用 @Valid 校验前端传递的参数阅读 4807
-
IDEA 中使用 Lombok 报找不到 get/set 错误的方法解决方法阅读 3853
-
Android adb 命令阅读 4552