赞
踩
KV 存储 HashMap - Rust语言圣经(Rust Course)
开头有个案例:
- fn main() {
- use std::collections::HashMap;
-
- let teams_list = vec![
- ("中国队".to_string(), 100),
- ("美国队".to_string(), 10),
- ("日本队".to_string(), 50),
- ];
-
- let mut teams_map = HashMap::new();
- for team in &teams_list {
- teams_map.insert(&team.0, team.1);
- }
-
- println!("{:?}",teams_map)
- }

这里for循环的的team是&(String,i32)类型,元组的借用类型,在使用如team.0,team.1时候,rust会自动解引用。
这个例子也可侧面知道rust会自动解引用元组引用:
- use std::collections::HashMap;
-
- fn main() {
- let tuple = ("中国".to_string(),10);
- let a = &tuple;
- println!("{}-{}",a.0,a.1);
-
- let mut hashmap = HashMap::new();
- //hashmap.insert(a.0,a.1); // 错误
-
- }
注释展开,此代码会报错:move occurs because `a.0` has type `String`, which does not implement the `Copy` trait。将其添加借用&可通过。
- use std::collections::HashMap;
-
- fn main() {
- let tuple = ("中国".to_string(),10);
- let a = &tuple;
- println!("{}-{}",a.0,a.1);
-
- let mut hashmap = HashMap::new();
- hashmap.insert(&a.0,a.1);
- }
注意到,insert会发生move,所以当心非copy类的所有权转移问题,案例中a.1是i32类型,可以copy。
另外注意,将引用类型数据放入hashmap中,需要考虑引用数据的生命周期。
关于unwrap_or方法,如果option<>是None时,unwrap_or返回提供的默认值,如unwrap_or(1)。
关于copied方法,将Option<&T>通过复制(copy)返回Option<T>,即引用类型转为值类型。
在kv中KV 存储 HashMap - Rust语言圣经(Rust Course)
let score: i32 = scores.get(&team_name).copied().unwrap_or(0);
该语句通过get方法返回一个Option<&i32>类型,经过copied(),转为Option<i32>类型,这样可以使用unwrap_or(0)方法。
另外,上文中:
- 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: Option<&i32> = scores.get(&team_name);
为什么get方法返回Option<&i32>值类型的引用?
解释:1.如果返回i32类型,那么会发生复制,哪怕微小的复制,在大量复制下也会降低性能,所以使用引用,避免内存分配和释放的负担 2.通过返回引用,可以让调用者决定是否需要复制值,是暂时使用值而不获取所有权
结果:
iter()等价于“&”(不可变引用迭代)
- for i in item.iter() {}
- for i in &item {}
- //对于iter()返回 std::slice::Iter<'_,T>,迭代器,产生&T类型的引用
- //就是这个i的数据类型
iter_mut()等价“&mut ”(可变引用迭代)
- for i in item.iter_mut() {}
- for i in &mut item {}
into_iter()等价“”(直接迭代、所有权迭代)
- for i in item.into_iter() {}
- for i in item {}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。