函数返回时,为什么从HashMap :: get借用没有结束? [英] Why does the borrow from `HashMap::get` not end when the function returns?
问题描述
这里是我的问题的模仿,当借贷的结账时间太晚了
Here is emulation of my problem, when a borrow ends too late
use std::collections::HashMap;
struct Item {
capacity: u64
}
struct Petrol {
name: String,
fuel: HashMap<&'static str, Item>
}
fn buy_gaz(p: &mut Petrol) {
match p.fuel.get("gaz") {
Some(gaz) => {
fire_petrol(p);
}
None => ()
}
}
fn fire_petrol(p: &mut Petrol) {
println!("Boom!");
p.fuel.remove("gaz");
p.fuel.remove("benzin");
}
fn main() {
let mut bt = Petrol {
name: "Britii Petrovich".to_string(),
fuel: HashMap::new()
};
bt.fuel.insert("gaz", Item { capacity: 1000 });
bt.fuel.insert("benzin", Item { capacity: 5000 });
buy_gaz(&mut bt);
}
编译时我得到:
note: previous borrow of `p.fuel` occurs here; the immutable borrow prevents subsequent moves or mutable borrows of `p.fuel` until the borrow ends
match p.fuel.get("gaz") {
^~~~~~
为什么借款这么晚才结束,而不是从HashMap::get
退出?我该如何解决我的情况?
Why does the borrow end so late and not on exit from HashMap::get
? How do I fix my case?
PS:我编辑了第一篇关于将结构添加到HashMap
的文章,因为下面的决定适用于简单的类型(我认为具有默认的Clone特性),但不适用于自定义结构
PS: I edited my first post for adding struct to HashMap
, because decision below worked for simply types (with default Clone trait, I think), but doesn't work for custom structures
推荐答案
If you look at the documentation of HashMap::get
you can see, that it returns an Option<&V>
. The reference into the map allows you to do zero-copy accesses into a hash-map. The downside is, as long as you have a reference, you cannot modify the hash map as that might invalidate your reference.
分支Some(gaz)
使绑定gaz
具有类型&u64
,其中引用指向您的哈希映射.如果将其更改为Some(&gaz)
,则将获得值的副本而不是引用,并且甚至可以在该分支内部修改哈希映射.
The branch Some(gaz)
causes the binding gaz
to have type &u64
, where the reference points into your hashmap. If you change that to Some(&gaz)
you get a copy of the value instead of a reference, and may modify the hash map even inside that branch.
这篇关于函数返回时,为什么从HashMap :: get借用没有结束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!