如何在 Rust 中创建一个具有默认值的 HashMap? [英] How does one create a HashMap with a default value in Rust?
问题描述
作为 Rust 的新手,我想知道如何使用键的默认值创建 HashMap
?例如,为 HashMap
中插入的任何键设置默认值 0
.
Being fairly new to Rust, I was wondering on how to create a HashMap
with a default value for a key? For example, having a default value 0
for any key inserted in the HashMap
.
在 Rust 中,我知道这会创建一个空的 HashMap:
In Rust, I know this creates an empty HashMap:
let mut mymap: HashMap<char, usize> = HashMap::new();
我希望为一组键维护一个计数器,其中一种方法似乎是:
I am looking to maintain a counter for a set of keys, for which one way to go about it seems to be:
for ch in "AABCCDDD".chars() {
mymap.insert(ch, 0)
}
有没有办法在 Rust 中以更好的方式做到这一点,也许类似于 Ruby 提供的东西:
Is there a way to do it in a much better way in Rust, maybe something equivalent to what Ruby provides:
mymap = Hash.new(0)
mymap["b"] = 1
mymap["a"] # 0
推荐答案
回答问题...
我希望为一组密钥维护一个计数器.
I am looking to maintain a counter for a set of keys.
那你想看看如何高效地从HashMap中查找和插入?.提示:*map.entry(key).or_insert(0) += 1
回答你提出的问题...
如何在 Rust 中创建一个具有默认值的 HashMap?
How does one create a HashMap with a default value in Rust?
不,HashMap
没有存储默认值的地方.这样做会导致该数据结构的每个用户分配空间来存储它,这将是一种浪费.您还必须处理没有合适默认值或无法轻松创建默认值的情况.
No, HashMap
s do not have a place to store a default. Doing so would cause every user of that data structure to allocate space to store it, which would be a waste. You'd also have to handle the case where there is no appropriate default, or when a default cannot be easily created.
相反,您可以使用 <查找值code>HashMap::get 并使用 Option::unwrap_or
:
Instead, you can look up a value using HashMap::get
and provide a default if it's missing using Option::unwrap_or
:
use std::collections::HashMap;
fn main() {
let mut map: HashMap<char, usize> = HashMap::new();
map.insert('a', 42);
let a = map.get(&'a').cloned().unwrap_or(0);
let b = map.get(&'b').cloned().unwrap_or(0);
println!("{}, {}", a, b); // 42, 0
}
如果 unwrap_or
对您的情况不起作用,则有几个类似的函数可能会:
If unwrap_or
doesn't work for your case, there are several similar functions that might:
当然,欢迎您将其封装在函数或数据结构中以提供更好的 API.
在 C++ 中有一个映射的概念 当一个键被插入时插入一个默认值访问.但这似乎总是有点漏洞:如果类型没有默认值怎么办?Rust 对映射类型的要求较低,并且对键的存在(或不存在)更加明确.
in C++ there's a notion of a map inserting a default value when a key is accessed. That always seemed a bit leaky though: what if the type doesn't have a default? Rust is less demanding on the mapped types and more explicit about the presence (or absence) of a key.
Rust 对此增加了额外的皱纹.实际上插入一个值需要简单地获取一个值也可以改变HashMap
.这将使对 HashMap
中值的任何现有引用无效,因为可能需要重新分配.因此,您将不再能够同时获得对两个值的引用!那将是非常严格的.
Rust adds an additional wrinkle to this. Actually inserting a value would require that simply getting a value can also change the HashMap
. This would invalidate any existing references to values in the HashMap
, as a reallocation might be required. Thus you'd no longer be able to get references to two values at the same time! That would be very restrictive.
这篇关于如何在 Rust 中创建一个具有默认值的 HashMap?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!