更新时间:2023-01-31 12:13:44
首先:您遇到的问题是 get
返回一个不可变的引用,而您尝试 insert代码>在那里.您可能希望使用
get_mut
来获取可以对其执行 insert
的可变引用.
First things first: the issue you have is that get
returns an immutable reference, and you try to insert
in there. You would want to use get_mut
to get a mutable reference on which insert
can be performed.
但是我建议改变设计:
这个方案的主要优点是数字 ID 比字符串更便宜/高效.
The main advantage of this scheme being that numerical IDs are much cheaper/efficient than Strings.
pub struct NationManager {
last_id: u32,
name_to_id: HashMap<String, u32>,
relationships: HashMap<(u32, u32), i8>, // (smaller ID, larger ID) -> score
}
查找两个国家之间的关系需要知道它们的 ID(在 name_to_id
中查找两次),然后查找关系分数.
Performing a look-up of the relationship between two countries will involve knowing their IDs (two look-ups in name_to_id
) and then looking up the relationship score.
关系
的扁平化也会极大地简化你的生成步骤:
The flattening of relationships
would tremendously simplify your generation step as well:
impl NationManager {
fn generate_relationships(&mut self) {
let random_rel: i8 = rand::thread_rng().gen_range(1, 101);
for source in 0..self.last_id {
for target in (source + 1)..self.last_id {
self.relationships.insert((source, target), random_rel);
}
}
}
}
注意:实际上,域分析也可以让我们使用更小的 ID;您不应该需要超过 65,535 个国家,所以 u16
绝对足够了,而且 u8
(255 个国家)可能也足够了(有 193 个国家)在联合国注册).
Note: actually, a domain analysis could let us use a much smaller ID as well; you shouldn't need more than 65,535 nations, so u16
is definitely sufficient, and it's likely that u8
(255 nations) would be sufficient as as well (there are 193 nations registered in the UN).