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

 

posted @ 2023-01-25 12:17  樊顺  阅读(80)  评论(0编辑  收藏  举报