

Rust Map指南:深入理解、轻松应用
source link: https://www.51cto.com/article/779170.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

大家好,我是渔夫。
今天我们来聊聊 Rust 中的map知识,在其他语言一样,Map 通常指的是一种数据结构和一系列操作,用于将一组值映射到另一组值或执行某些操作,也就是我们常说的键值对。接下来一起探讨 Rust 中map 的基本用法,和常见操作以及一些有用的技巧。

什么是map?
在 Rust 中map是一种非常重要数据结构,和其他语言类似,也是一种键-值存储的集合。它能够允许你将一个键与一个值相关联,然后就方便通过键来检索值。下面是简单例子,在 Rust中,map通常通过std::collections::HashMap来实现。
use std::collections::HashMap;
fn main() {
let mut scores = HashMap::new();
scores.insert("Alice", 100);
scores.insert("Bob", 90);
scores.insert("Charlie", 95);
let alice_score = scores.get("Alice");
match alice_score {
Some(score) => println!("Alice's score is: {}", score),
None => println!("Alice's score is not available."),
}
}
运行结果:
Alice's score is: 100
[Done] exited with code=0 in 0.689 seconds
在上面的示例中,创建了一个名为scores的HashMap,并且将三个键值对插入其中。使用get方法来检索 "Alice" 的分数。
- 其中 match alice_score { ... } ,作用是它用于匹配alice_score的值,并根据匹配结果执行不同的代码块。
- Some(score) => println!("Alice's score is: {}", score):这是一个匹配分支。它检查alice_score是否包含Some值。
- None => println!("Alice's score is not available."):这是另一个匹配分支,用于处理alice_score为None的情况。
在 Rust 语言还是挺好用的这些匹配规则。
1.插入和更新值
如果你要向HashMap中插入新的键值对,可以使用insert方法。如果键已经存在,它将把值覆盖掉。
scores.insert("Alice", 105); // 更新Alice的分数
scores.insert("Eve", 80); // 插入新的键值对
2.获取值
要获取HashMap中的值,可以使用get方法,和 Java 是不是很类似。如果键不存在,它会返回一个Option。
// let alice_score = scores.get("test"); // 键不存在,将会打印出 None
let alice_score = scores.get("Alice");
match alice_score {
Some(score) => println!("Alice's score is: {}", score),
None => println!("Alice's score is not available."),
}
3.删除值
还可以对HashMap中的键值对进行删除操作,可以使用remove方法。
scores.remove("Bob");
除上面增删改操作,还有一个重要的,如果遍历HashMap中的所有键值,这里使用迭代器。
use std::collections::HashMap;
fn main() {
let mut scores = HashMap::new();
scores.insert("Alice", 100);
scores.insert("Bob", 90);
scores.insert("Charlie", 95);
scores.insert("Alice", 105);
// 遍历
for (key, value) in &scores {
println!("{}: {}", key, value);
}
}
遍历结果:
Charlie: 95
Alice: 105
Bob: 90
[Done] exited with code=0 in 0.521 seconds
除了上面介绍的常见操作以外,其实HashMap还提供了许多有用的方法,比如查找键是否存在、获取键的集合、获取值的集合等等。这些方法在实际开发中,可以根据需要灵活使用,非常方便。
5.默认值
首先,来看第一个,默认值,这个作用是如果键不存在,你可以使用entry方法来设置默认值。
let charlie_score = scores.entry("Charlie").or_insert(0);
6.更新值
另外还可以使用entry方法来更新值,这就更加有意思了,可以让你在在原有值的基础上执行操作,用起来也是挺爽是不是。
let bob_score = scores.entry("Bob").or_insert(0);
*bob_score += 5;
最后一个,如果需要按键或值对HashMap进行排序,你可以将它们提取到Vec中,然后使用sort方法来排序。
let mut score_vec: Vec<(&str, &i32)> = scores.iter().collect();
score_vec.sort_by(|a, b| b.1.cmp(a.1)); // 按值降序排序
- scores.iter() 是使用HashMap的iter方法,返回一个迭代器,该迭代器可以用于遍历HashMap中的键值对。
- collect方法,作用是将迭代器中的元素收集到一个容器中,这里是将键值对收集到了score_vec向量中。
然后现在score_vec向量包含了HashMap中的键值对,然后使用sort_by方法来排序向量中的元素。其实就是通过一个闭包完成的,该闭包接受两个参数a和b,它们分别代表向量中的两个元素,每个元素都是一个包含键和值的元组。
元素比较使用cmp方法,它返回一个排序顺序,对于整数的话,它可以是Ordering::Less、Ordering::Equal或Ordering::Greater,分别表示“小于”、“等于”或“大于”这样比较。
总结, Rust 中的HashMap是一个强大的数据结构,用于存储和操作键值对。今天主要介绍常规用法、常见操作和一些技巧,希望对你有所帮助。
Recommend
-
9
by zhangxinxu from http://www.zhangxinxu.com 本文地址:http://www.zhangxinxu.com/wordpress/?p=384...
-
9
原文标题:Understanding Rust Lifetimes 原文链接:https://medium.com/nearprotocol/understanding-rust-lifetimes-e813bcd405fa 公众号:Rust 碎碎念 翻译 by:Praying 从 C++来到 Rust 并需要学习生...
-
13
深入理解分布式技术 - 从区块链技术看分布式理论的应用_小工匠-CSDN博客 简介:区块链技术是应用程序基础,它超越了比特币本身。这些技术能促进智能交易、分布式股权发布和资产转移。彩...
-
10
原文链接:Understanding Rust futures by going way too deep。 译者注:原文大量的引入了有趣的对话,迫于排版问题这里不进行翻译,必要的对话通过...
-
7
点击上方蓝字关注我,知识会给你力量
-
8
深入理解 Java Map发表于2020-01-02|更新于2021-10-29|Java字数总计:2.4k|阅读时长:7分钟|阅读量:59 在日常的编程活动中,使用 Map...
-
6
深入理解Go-map原理剖析 发表于 2019-10-08 ...
-
8
Map is like a Go map[interface{}]interface{} but is safe for concurrent use by multiple goroutines without additional locking or coordination. Loads, stores, and deletes run in amortized constant time.
-
7
通过本篇内容,你可以学到如何解决 Logstash 的常见问题、理解 Logstash 的运行机制、集群环境下如何部署 ELK Stack。在使用 Logstash 遇到了很多坑,本篇也会讲解解决方案。日志记录的格式复杂,正则表达式非常磨人。服务日志有多种格...
-
9
深入理解Elasticsearch的基本搜索:轻松找到你所需的信息 作者:树言树语Tree 2023-10-08 08:51:14 开源 下面将围绕 Elasticsearch...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK