我有一个函数,它接受了一个借用的 HashMap
,我需要通过键访问值。为什么键和值是按引用传递而不是按值传递呢?
我的简化代码:
fn print_found_so(ids: &Vec<i32>, file_ids: &HashMap<u16, String>) {
for pos in ids {
let whatever: u16 = *pos as u16;
let last_string: &String = file_ids.get(&whatever).unwrap();
println!("found: {:?}", last_string);
}
}
为什么我必须将键指定为引用,即使用
file_ids.get(&whatever).unwrap()
而不是file_ids.get(whatever).unwrap()
?据我所知,
last_string
必须是&String
类型,即 借用字符串,因为拥有该集合的是借用状态。这样理解对吗?与上面一点类似,我是否正确地认为
pos
的类型是&u16
,因为它从ids
中获取了借用值?
&
对我来说更清晰一些。 - stej