走进 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);
阅读 3123 · 发布于 2020-07-16
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb扫描下方二维码关注公众号和小程序↓↓↓

昵称:
随便看看
换一批
-
Spring Boot 分层构建 Docker 镜像阅读 558
-
Spring Boot 拦截器中 handler 的几种类型阅读 473
-
IDEA Cannot resolve plugin org.apache.maven.plugins:maven-clean-plugin:2.5阅读 2062
-
Spring Boot 整合多数据源阅读 1347
-
Windows 安装 tcpdump阅读 7048
-
Docker 部署 Swagger Editor阅读 399
-
Elasticsearch 全文搜索 query->match阅读 1341
-
Python UnicodeDecodeError: 'gbk' codec can't decode byte 0x80阅读 3441
-
IDEA Debug 时模拟抛出异常阅读 1533
-
Linux cron 任务定时删除 5 天前的日志阅读 1194