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 的调试. 配置调试器不难,但仍然需要几个步骤.我已经完整配置了好几次.我正在写 ...
随机推荐
- Pytorch中stack()方法的理解
Torch.stack() 1. 概念 在一个新的维度上连接一个张量序列 2. 参数 tensors (sequence)需要连接的张量序列 dim (int)在第dim个维度上连接 注意输入的张量s ...
- Git基本教程
git的发展 Git 两周开发 Linus开发,主要是为了管理大量人员维护代码 Git分布式版本控制系统 基本命令 history:查看之前用过的命令 vimtutor git配置 查看配置 git ...
- git stash 存储命令
应用场景 一.当你接到一个修复紧急 bug 的任务时候,一般都是先创建一个新的 bug 分支来修复它,然后合并,最后删除.但是,如果当前你正在开发功能中,短时间还无法完成,无法直接提交到仓库,这时候可 ...
- java.lang.NoSuchFieldError: REFLECTION
2020-09-14 09:13:21.415 INFO org.apache.cxf.service.factory.ReflectionServiceFactoryBean Line:457 - ...
- oracle的 listagg() WITHIN GROUP () 行转列函数的使用
1.使用条件查询 查询部门为20的员工列表 -- 查询部门为20的员工列表 SELECT t.DEPTNO,t.ENAME FROM SCOTT.EMP t where t.DEPTNO ...
- 菜鸡的Java笔记 生产者与消费者
生产者与消费者 代码要求知道做什么用即可 线程间的通讯问题以及 Object 类的支持 基础模型 现在希望实现一种数据的生产和取出的操作 ...
- 【JVM】JVM 概述、内存结构、溢出、调优(基础结构+StringTable+Unsafe+ByteBuffer)
什么是 JVM ? 定义 Java Virtual Machine - java 程序的运行环境(java 二进制字节码的运行环境) 好处 一次编写,到处运行 自动内存管理,垃圾回收功能 数组下标越界 ...
- 行星万象表白墙微信小程序、社交微信小程序,后台完整,支持多区域运营,扫码体验。
简介 中国目前大概有5000个表白墙,累计用户近3000万,是一个庞大的群体,但现在大都以微信朋友圈为基础进行信息中转,但是这种模式经营者和用户都不友好,尤其是经营者无法变现,用户无法公开评论,这些种 ...
- [loj3527]地牢游戏
当英雄能力值$\ge 10^{7}$时,即能战胜所有敌人,简单预处理即可 若英雄能力值在$[2^{k},2^{k+1})$中,对敌人分类讨论: 1.若$s_{i}\le 2^{k}$,其必然会战胜这些 ...
- [bzoj1853]幸运数字
容易发现幸运数字只有1024个,暴力标记倍数还是会tle的 容斥,即从中任选i个的lcm,复杂度为$o(2^1024)$ 剪枝一:当答案超过1024就不用算了 剪枝二:当某个数是另一个数的倍数时就删掉 ...