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的更多相关文章

  1. 【Rust】使用HashMap解决官方文档中的闭包限制

    问题概述 值缓存是一种更加广泛的实用行为,我们可能希望在代码中的其他闭包中也使用他们.然而,目前 Cacher 的实现存在两个小问题,这使得在不同上下文中复用变得很困难. 第一个问题是 Cacher  ...

  2. InfoQ中文站特供稿件:Rust编程语言的核心部件

    本文为InfoQ中文站特供稿件.首发地址为: http://www.infoq.com/cn/articles/rust-core-components .如需转载.请与InfoQ中文站联系. 原文发 ...

  3. Rust入坑指南:鳞次栉比

    很久没有挖Rust的坑啦,今天来挖一些排列整齐的坑.没错,就是要介绍一些集合类型的数据类型."鳞次栉比"这个标题是不是显得很有文化? 在Rust入坑指南:常规套路一文中我们已经介绍 ...

  4. rust 高级话题

    目录 rust高级话题 前言 零大小类型ZST 动态大小类型DST 正确的安装方法 结构体 复制和移动 特征对象 引用.生命周期.所有权 生命周期 错误处理 交叉编译 智能指针 闭包 动态分派和静态分 ...

  5. rust语法

    目录 rust语法 前言 一.数据类型 1.1 标量scalar 1.2 复合compound 1.3 切片slice 1.4 引用(借用)reference 1.5 智能指针smart pointe ...

  6. Rust基础

    一:编译器 Rust的编译器叫rustc,类似javac一样,负责将源代码编译成可执行文件或者库文件(.a/.so/.lib/.dll等) 二:核心库和标准库 Rust语言由核心库和标准库组成,核心库 ...

  7. Rust学习笔记2

    继续继续... 转眼都开学啦... Building Blocks 2 building blocks里讲了一些关于Log structure storage的东西,这也是用于在硬盘上持久化KvSto ...

  8. Rust学习笔记1

    这是一份不错的rust教程,目前包括4个block和4个project.全部完成后可以用rust实现一个简单的key-value存储引擎. 注意:Windows下rust貌似会遇到一些bug,强烈建议 ...

  9. [翻译]使用Visual Studio Code怎样调试Rust

    我将 Visual Studio Code 作为Rust首选编辑器.遗憾的是 VS Code 不能非常好地完成 Rust 的调试. 配置调试器不难,但仍然需要几个步骤.我已经完整配置了好几次.我正在写 ...

随机推荐

  1. Part 15 AngularJS ng init directive

    The ng-init directive allows you to evaluate an expression in the current scope.  In the following e ...

  2. [atARC124F]Chance Meeting

    为了方便,不妨先将$n$和$m$都减小1,其意义即为移动的次数 注意到老鼠向下移动和猫向上移动对于第2个条件是等价的,对于第1个条件即要求都恰好移动$n$次,那么对应的方案数即为${2n\choose ...

  3. [noi713]魔法

    分治,维护一个dp数组,当递归到区间[l,r]时,需要保证这个dp数组维护的是除去[l,r]以外的dp数组维护其实很简单,就是递归左区间是先将右区间加入,然后再将左区间加入(要先复原)然后递归右区间即 ...

  4. [bzoj1106]立方体大作战

    先贪心,容易发现如果两个点中间没有点对,那么一定可以先把这两个点消掉分析一下,就可以发现这样两个点的答案就是这两个点对中间不成对的点数量扫描过去,线段树维护每一个点的权值(是否会被算入答案)即可 1 ...

  5. 【JavaSE】字符编码和存储编码

    字符编码和存储编码 2019-07-15  22:34:51  by冲冲 1. 英文字母和中文汉字在不同字符集编码下的字节数不同. 英文字母 字节数 : 1; 编码:GB2312 字节数 : 1; 编 ...

  6. Flink 实践教程-入门(8): 简单 ETL 作业

    作者:腾讯云流计算 Oceanus 团队 流计算 Oceanus 简介 流计算 Oceanus 是大数据产品生态体系的实时化分析利器,是基于 Apache Flink 构建的具备一站开发.无缝连接.亚 ...

  7. 十行HTML实现增强现实--思途青岛

    你想通过网络实现增强现实吗?现在你只需要 10 行 HTML 代码!真的!让我带你看一看代码,非常简单.我们最近发布了AR.js.你不需要安装任何应用,用你的手机通过网络就能体验到强大的增强现实.但让 ...

  8. ABC 210

    A 按题意模拟. scanf("%lld%lld%lld%lld",&n,&a,&x,&y); std::cout<<n * x - ( ...

  9. 洛谷 P4646 - [IOI2007] flood 洪水(拆点+bfs)

    题面传送门 一道挺有意思的题(?) orz djq yyds %%%%%%%%%%%%%%%%%% 首先一个很直观的想法是将每个房间看作一个节点,在有墙的房间旁边连边权为 \(1\) 的边然后 bfs ...

  10. canvas 基本介绍

    # canvas 基本功能介绍 - canvas 能做什么 1. 绘制简单图形线条 2. 裁剪图片 - 开始绘制画布 新建html文档添加 canvas标签 ```html <div style ...