3.3 rust HashMap
The type HashMap<K, V> stores a mapping of keys of type K to values of type V. It does this via a hashing function, which determines how it places these keys and values into memory.
use std::collections::HashMap;
pub fn add1(){
let mut scores = HashMap::new();
scores.insert(String::from("Blue"),10);
scores.insert(String::from("Yellow"),50);
}
Just like vectors, hash maps store their data on the heap. This HashMap has keys of type String and values of type i32. Like vectors, hash maps are homogeneous: all of the keys must have the same type, and all of the values must have the same type.
pub fn get_map(){
let teams = vec![String::from("Blue"), String::from("Yellow")];
let initial_scores = vec![10, 50];
let _scores: HashMap<_, _> =
teams.into_iter().zip(initial_scores.into_iter()).collect();
}
Hash Maps and Ownership
简单类型复制,复合类型移动并具有ownership关系,引用类型除外
fn main() {
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);
// field_name and field_value are invalid at this point, try using them and
// see what compiler error you get!
}
We aren’t able to use the variables field_name and field_value after they’ve been moved into the hash map with the call to insert.
If we insert references to values into the hash map, the values won’t be moved into the hash map. The values that the references point to must be valid for at least as long as the hash map is valid.
Accessing Values in a Hash Map
pub fn m1(){
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);
println!("{:?}",score);
println!("--------------------------");
for (key, value) in &scores {
let val = value + 1;
println!("{}: {}", key, val);
}
}
Here, score will have the value that’s associated with the Blue team, and the result will be Some(&10). The result is wrapped in Some because get returns an Option<&V>; if there’s no value for that key in the hash map, get will return None
$ cargo run
Compiling a_map v0.1.0 (/opt/wks/rust/a_map)
Finished dev [unoptimized + debuginfo] target(s) in 0.28s
Running `target/debug/a_map`
------------------
Some(10)
--------------------------
Yellow: 51
Blue: 11
Updating a Hash Map
//存在就覆盖
pub fn m2(){
let mut scores = HashMap::new();
scores.insert(String::from("Blue"),10);
scores.insert(String::from("Blue"),50); let team_name = String::from("Blue");
let score = scores.get(&team_name); println!("{:?}",score);
}
Some(50)
//存在就跳过
pub fn m3(){
let mut scores = HashMap::new();
scores.insert(String::from("Blue"),10);
scores.entry(String::from("Blue")).or_insert(50); let team_name = String::from("Blue");
let score = scores.get(&team_name); println!("{:?}",score);
}
Some(10)
3.3 rust HashMap的更多相关文章
- 【Rust】使用HashMap解决官方文档中的闭包限制
问题概述 值缓存是一种更加广泛的实用行为,我们可能希望在代码中的其他闭包中也使用他们.然而,目前 Cacher 的实现存在两个小问题,这使得在不同上下文中复用变得很困难. 第一个问题是 Cacher ...
- InfoQ中文站特供稿件:Rust编程语言的核心部件
本文为InfoQ中文站特供稿件.首发地址为: http://www.infoq.com/cn/articles/rust-core-components .如需转载.请与InfoQ中文站联系. 原文发 ...
- Rust入坑指南:鳞次栉比
很久没有挖Rust的坑啦,今天来挖一些排列整齐的坑.没错,就是要介绍一些集合类型的数据类型."鳞次栉比"这个标题是不是显得很有文化? 在Rust入坑指南:常规套路一文中我们已经介绍 ...
- rust 高级话题
目录 rust高级话题 前言 零大小类型ZST 动态大小类型DST 正确的安装方法 结构体 复制和移动 特征对象 引用.生命周期.所有权 生命周期 错误处理 交叉编译 智能指针 闭包 动态分派和静态分 ...
- rust语法
目录 rust语法 前言 一.数据类型 1.1 标量scalar 1.2 复合compound 1.3 切片slice 1.4 引用(借用)reference 1.5 智能指针smart pointe ...
- Rust基础
一:编译器 Rust的编译器叫rustc,类似javac一样,负责将源代码编译成可执行文件或者库文件(.a/.so/.lib/.dll等) 二:核心库和标准库 Rust语言由核心库和标准库组成,核心库 ...
- Rust学习笔记2
继续继续... 转眼都开学啦... Building Blocks 2 building blocks里讲了一些关于Log structure storage的东西,这也是用于在硬盘上持久化KvSto ...
- Rust学习笔记1
这是一份不错的rust教程,目前包括4个block和4个project.全部完成后可以用rust实现一个简单的key-value存储引擎. 注意:Windows下rust貌似会遇到一些bug,强烈建议 ...
- [翻译]使用Visual Studio Code怎样调试Rust
我将 Visual Studio Code 作为Rust首选编辑器.遗憾的是 VS Code 不能非常好地完成 Rust 的调试. 配置调试器不难,但仍然需要几个步骤.我已经完整配置了好几次.我正在写 ...
随机推荐
- glibc memcpy() 源码浅谈
其实我本来只是想搞懂为什么memcpy()函数的参数类型是void *的: 我以为会在memcpy()源码中能找到答案,其实并没有,void *只是在传递参数的时候起了作用,可以让memcpy()接受 ...
- MySQL高级篇 | 索引介绍
前言 性能下降SQL慢的原因 查询语句写的烂 索引失效 单值索引 复合索引 关联查询太多join(设计缺陷或不得已的需求) 服务器调优及各个参数设置(缓冲.线程数等) 索引是什么 MySQL官方对索引 ...
- [Aizu1410]Draw in Straight Lines
注意到当操作确定后,显然操作顺序总是涂黑色的1操作->涂白色的1操作->2操作 用$b/w_{r/c}(i,j)$表示$(i,j)$是否被黑色/白色 横着/竖着 涂过(1表示涂过,0表示没 ...
- FastAPI(六十二)实战开发《在线课程学习系统》需求分析
前言 基础的分享我们已经分享了六十篇,那么我们这次分享开始将用一系列的文章分享实战课程.我们分享的系统是在线学习系统.我们会分成不同的模块进行分享.我们的目的是带着大家去用fastapi去实战一次,开 ...
- 学以致用 | Redis概念与简单实操
Redis概念 Redis是一个由C语言编写.基于key-value存储结构的开源NoSQL数据库,其读写速度为10万次/秒,这个速度已经远远大于传统的关系型数据库. 使用场景 在高并发的情况下,可将 ...
- [SQL]SQL Server 锁表
-- 查看被锁表: SELECT request_session_id spid, -- 锁表进程 OBJECT_NAME(resource_associated_entity_id) tableNa ...
- 8.2 k8s 基于StatefulSet运行mysql 一主多从 ,数据通过pv/pvc结合NFS服务器持久化
1.准备mysql和xtrabackup镜像 下载mysql官方镜像并上传到本地harbor docker pull mysql:5.7 docker tag m ysql:5.7 192.168.1 ...
- 如何在 Kubernetes 集群中玩转 Fluid + JuiceFS
作者简介: 吕冬冬,云知声超算平台架构师, 负责大规模分布式机器学习平台架构设计与功能研发,负责深度学习算法应用的优化与 AI 模型加速.研究领域包括高性能计算.分布式文件存储.分布式缓存等. 朱唯唯 ...
- 洛谷 P7155 [USACO20DEC] Spaceship P(dp)
Portal Yet another 1e9+7 Yet another 计数 dp Yet another 我做不出来的题 考虑合法的按键方式长啥样.假设我们依次按下了 \(p_1,p_2,\dot ...
- Codeforces 1406E - Deleting Numbers(根分+数论)
Codeforces 题面传送门 & 洛谷题面传送门 一道个人感觉挺有意思的交互题,本人一开始想了个奇奇怪怪的做法,还以为卡不进去,结果发现竟然过了,而且还是正解( 首先看到这类题目可以考虑每 ...