美文网首页
Rust 入门 - HashMap

Rust 入门 - HashMap

作者: Lee_dev | 来源:发表于2021-06-01 11:21 被阅读0次

导入库

use std::collections::HashMap;

使用

let mut scores = HashMap::new();
scores.insert("bad".to_string(), 10);
scores.insert("googd".to_string(), 100);
println!("scores = {:#?}", scores);

vector 和 hashmap 数据都在堆上

用队伍列表和分数列表创建哈希 map

let teams = vec!["blue".to_string(), "red".to_string()];
let scores = vec![10, 50];
let res: HashMap<_, _> = teams.iter().zip(scores.iter()).collect();
println!("res = {:#?}", res);

哈希 map 和所有权

对于像 i32 这样的实现了 Copy trait 的类型,其值可以拷贝进哈希 map。对于像 String 这样拥有所有权的值,其值将被移动而哈希 map 会成为这些值的所有者

let s1 = "hello".to_string();
let s2 = "world".to_string();
let mut map = HashMap::new();
map.insert(s1, s2);
// println!("s1 = {}, s2= {}", s1, s2); 被借用
println!("map = {:#?}", map);

访问哈希 map 中的值

let mut res = HashMap::new();
res.insert("good".to_string(), 100);
res.insert("bad".to_string(), 10);
let k = "good".to_string();
let v = res.get(&k);
match v {
    Some(value) => println!("value = {}", value),
    None => println!("none"),
}

for (key, value) in &res {
    println!("{}: {}", key, value);
}

只在键没有对应值时插入

let mut scores = HashMap::new();
scores.insert("b".to_string(), 100);
scores.entry("b".to_string()).or_insert(10);
scores.entry("r".to_string()).or_insert(90);
println!("scores = {:#?}", 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 = {:#?}", map);

相关文章

  • Rust 入门 - HashMap

    导入库 使用 vector 和 hashmap 数据都在堆上 用队伍列表和分数列表创建哈希 map 哈希 map ...

  • rust学习总结002

    rust 哈希表常用操作 获取 HashMap 成员 hashMap[key]hashMap.get(key)

  • Rust 从基础到实践(15) hashmap

    要使用 Rust 的 hashmap 我们首先需要引入一下 hashmap 才可以使用。hashMap 是一种将 ...

  • Rust 问答之 Cargo 是什么

    Cargo:Rust 的构建工具和包管理器 文章标题来自于 Rust 官网: 入门 - Rust 程序设计语言 在...

  • Rust CLI应用程序的入门模板:rust-starter

    rust-starter是一个创建Rust CLI应用程序的入门模板。 特性 Clap[https://githu...

  • Rust 入门 (Rust Rocks)

    缘起 实践出真知快速获取澄清概念OwnershipMoveReferenceMutable reference解释...

  • Rust语言入门

    一、简介 Rust是Mozilla公司推出的一门全新的编程语言,1.0版本于2015年5月15日正式对外发布。作为...

  • Rust 入门 - 方法

    函数/方法 无返回值 有返回值 语句不会返回值,表达式会返回值

  • Rust 入门 - Slice

    Slice 另一个没有所有权的数据类型是 slice。slice 允许你引用集合中一段连续的元素序列,而不用引用整...

  • Rust 入门 - 类型

    类型 布尔类型 char类型, 在 Rust 中 char 是32位的 数字类型i8, i16, i32, i64...

网友评论

      本文标题:Rust 入门 - HashMap

      本文链接:https://www.haomeiwen.com/subject/wlswsltx.html