Rust中 HashMap 的基础用法示例
代码:
use std::collections::HashMap; fn main() { // 创建一个hash-map,key为字符串类型,value为无符号整数类型 let mut map: HashMap<&str, u32> = HashMap::new(); // 插入一条记录 // pub fn insert(&mut self, k: K, v: V) -> Option<V> let inserted = map.insert("price", 100); println!("insert() => {:?}", inserted); // 查询上一条记录的值 // pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V> let price = map.get(&"price"); println!("get() => {:?}", price); // 与get()方法不同,其get_mut()方法会返回该记录的可变引用 // pub fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut V> let mut_price = map.get_mut(&"price"); println!("get_mut() => {:?}", mut_price); // 删除一个键 // pub fn remove<Q: ?Sized>(&mut self, k: &Q) -> Option<V> let deleted = map.remove(&"price"); println!("remove() => {:?}", deleted); // 检查被查询的键是否存在 // pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool let has_price = map.contains_key(&"price"); println!("contains_key() => {}", has_price); map.insert("sales", 999); // 获取map中记录(键值对)的数量 // pub fn len(&self) -> usize let keys_cnt = map.len(); println!("len() => {}", keys_cnt); // 清空map中的记录 // pub fn clear(&mut self) map.clear(); println!("map's len after clear() => {}", map.len()); // 检查map是否为空 // pub fn is_empty(&self) -> bool let is_empty = map.is_empty(); println!("is_empty() => {}", is_empty); // 获取当前key的使用状态 // 如果已经存在该key,则返回Occupied(OccupiedEntry<'a, K, V>); // 如果还不存在,则返回Vacant(VacantEntry<'a, K, V>) // pub fn entry(&mut self, key: K) -> Entry<'_, K, V> let stat1 = map.entry("price"); println!("entry() => {:?}", stat1); // 通过插入默认值(如果为空)确保值在条目中,并返回对条目中值的可变引用。 // "price"存在,则直接返回其值;否则,先insert再返回其值; // pub fn or_insert(self, default: V) -> &'a mut V map.entry("price").or_insert(100); // 插入后的状态(比较stat1) let stat2 = map.entry("price"); println!("entry() => {:?}", stat2); // 遍历hash-map for (key, value) in map { println!("key: {:?}, value: {:?}", key, value); } }
Rust标准库文档:
https://doc.rust-lang.org/stable/std/index.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!