【发布时间】:2016-10-09 18:13:10
【问题描述】:
我有一个函数需要一个借来的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获取借用值?
【问题讨论】:
-
好的,知道了。来自其他开发世界,这有时可以帮助我更清楚地看到
&标志..
标签: collections rust ownership borrowing