[英]How can I store multiple elements in a Rust HashMap for the same key?
I have a HashMap<u32, Sender>
.我有一个
HashMap<u32, Sender>
。 Sender
is a open connection object and the key is a user id. Sender
是一个开放的连接对象,key 是一个用户 ID。 Each user can connect from multiple devices.每个用户可以从多个设备连接。 I need to store all possible open connections for the same user id.
我需要为同一个用户 ID 存储所有可能的打开连接。 After this I can iterate and send messages to all open connections for same user.
在此之后,我可以迭代并向同一用户的所有打开的连接发送消息。
The above HashMap
only stores each user id and connection once.上面的
HashMap
只存储每个用户 id 和连接一次。 I need to get one key with multiple values.我需要获得一个具有多个值的键。 How can I make the value into a list or an array, so I can see which connections exist and send to them all?
如何将值放入列表或数组中,以便我可以查看存在哪些连接并将其发送给所有连接?
I am not talking about different value types, like enums.我不是在谈论不同的值类型,比如枚举。 I am talking about the same type values but more than one.
我说的是相同类型的值,但不止一个。 Maybe
HashMap
is not designed for this?也许
HashMap
不是为此而设计的?
Alternative ideas are also welcomed.也欢迎其他想法。
To do this with a HashMap
you should use a Vec
as the values, so that each key can point to multiple Sender
s.要使用
HashMap
执行此操作,您应该使用Vec
作为值,以便每个键可以指向多个Sender
。 The type then would be HashMap<u32, Vec<Sender>>
.然后类型将是
HashMap<u32, Vec<Sender>>
。
Using this structure, just using insert()
can get clunky when you need to mutate the values like this, but instead you can use the Entry
API for retrieving and updating records in one go.使用这种结构,当您需要像这样改变值时,仅使用
insert()
会变得笨拙,但是您可以使用Entry
API 一次性检索和更新记录。 For example:例如:
let mut hash_map: HashMap<u32, Vec<Sender>> = HashMap::new();
hash_map.entry(3)
// If there's no entry for key 3, create a new Vec and return a mutable ref to it
.or_default()
// and insert the item onto the Vec
.push(sender);
You could also use the multimap
crate , which does something similar under the hood, but adds a layer of abstraction.您也可以使用
multimap
crate ,它在multimap
做类似的事情,但增加了一个抽象层。 You might find it easier to work with:您可能会发现使用以下工具更容易:
let mut multi_map = MultiMap::new();
multi_map.insert(3, sender_1);
multi_map.insert(3, sender_2);
The method multi_map.get(key)
will the first value with that key, while multi_map.get_vec(key)
will retrieve all of them.方法
multi_map.get(key)
将使用该键的第一个值,而multi_map.get_vec(key)
将检索所有这些值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.