您的位置 首页 php

Rust 头铁之路 | 哈希 map 储存键值对

2022年03月29日 日更 90 / 100 天

昨天学到 字符串新建与更新的语法。今天来学习哈希表。哈希、map、对象、哈希表或者关联数组哈希 map 可以用于需要任何类型作为键来寻找数据的情况,而不是像 vector 那样通过索引

01

新建一个哈希表

 use std::collections::HashMap;

let mut scores = HashMap::new();

scores.insert(String::from("Blue"), 10);
scores.insert(String::from("Yellow"), 50);

// 使用 vector 创建哈希
use std::collections::HashMap;
let teams = vec![String::from("Blue"), String::from("Yellow")];
let initial_scores = vec![10, 50];

let scores: HashMap<_, _> = teams.iter().zip(initial_scores.iter()).collect();
  

02

哈希 Map 和所有权。在把有所有权的值(String)写入 map 时,这些值便不能再使用

 use std::collections::HashMap;

let field_name = String::from("Favorite color");
let field_value = String::from("Blue");

let mut map = HashMap::new();
map.insert(field_name, field_value);
// 之后再访问 file_name / field_value 便会出问题
  

03

访问哈希 map 中的值

 use std::collections::HashMap;

let mut scores = HashMap::new();

scores.insert(String::from("Blue"), 10);
scores.insert(String::from("Yellow"), 50);

let team_name = String::from("Blue");
let score = scores.get(&team_name); // get() 方法访问

for (key, value) in &scores { // for 循环遍历
    println!("{}:{}", key, value);
}
  

04

更新哈希 map

  • 覆盖一个值
 use std::collections::HashMap;

let mut scores = HashMap::new();
scores.insert(String::from("Blue"), 10);
scores.insert(String::from("Blue"), 50);
println!("{:?}", scores); // 打印 {"Blue", 50}
  
  • 只在键不存在时插入
 use std::collections::HashMap;
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); // 打印 {"Yellow": 50, "Blue": 10}
  
  • 根据旧值更新一个值
 use std::collections::HashMap;

let text = "hello world wonderfull world";
let mut map = HashMap::new();

for word in text.split_whitespace() {
let count = map.entry(word).or_insert(0);
    *count += 1;
}

println!("{:?}", map); // 打印 {"world": 2, "hello": 1, "wonderful": 1}
  

总结

使用哈希表存储键值对,Rust 跟 PHP 相比,的确 PHP 很灵活。Rust 的这些看着很头大。


上一篇:Rust 头铁之路 | 一次周回顾周复盘


我是【明哥我来】,你的点赞关注,就是我的前进动力。

文章来源:智云一二三科技

文章标题:Rust 头铁之路 | 哈希 map 储存键值对

文章地址:https://www.zhihuclub.com/79668.shtml

关于作者: 智云科技

热门文章

网站地图