ste*_*tej 3 collections ownership rust borrowing
我有一个借用的功能,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);
}
}
Run Code Online (Sandbox Code Playgroud)
为什么我必须指定密钥作为参考,即file_ids.get(&whatever).unwrap()代替file_ids.get(whatever).unwrap()?
据我所知,它last_string必须是类型&String,意思是借用的字符串,因为拥有的集合是借用的.是对的吗?
与上述点类似,我假设pos是类型是正确的,&u16因为它需要借来的值ids?
考虑将参数作为引用或值传递的语义:
作为参考:没有所有权转移.被调用的函数只是借用参数.
作为值:被调用的函数获取参数的所有权,并且可能不再被调用者使用.
由于函数HashMap::get不需要密钥的所有权来查找元素,因此选择了限制较少的传递方法:通过引用.
此外,它不返回元素的值,只返回引用.如果它返回了该值,则其中的值HashMap将不再由其拥有HashMap,因此将来无法访问.