如何在同一个密钥的Rust HashMap中存储多个元素? [英] How can I store multiple elements in a Rust HashMap for the same key?

查看:164
本文介绍了如何在同一个密钥的Rust HashMap中存储多个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 HashMap< u32,Sender> 发件人是一个打开的连接对象,键是一个用户ID。每个用户可以从多个设备连接。我需要为同一用户ID存储所有可能的打开的连接。之后,我可以迭代并向同一用户的所有打开的连接发送消息。

I have a HashMap<u32, Sender>. Sender is a open connection object and the key is a user id. Each user can connect from multiple devices. I need to store all possible open connections for the same user id. After this I can iterate and send messages to all open connections for same user.

上面的 HashMap 仅存储每个用户ID和连接一次。我需要一个具有多个值的键。如何将值放入列表或数组中,以便查看存在的连接并将其全部发送给它们?

The above HashMap only stores each user id and connection once. 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?

我不是在谈论不同的值类型,像枚举。我说的是相同的类型值,但不止一个。也许 HashMap 不是为此设计的吗?

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 进行此操作,应使用 Vec 作为值,以便每个键都可以指向多个 Sender s。这样的类型将是 HashMap< u32,Vec< Sender>>

To do this with a HashMap you should use a Vec as the values, so that each key can point to multiple Senders. The type then would be HashMap<u32, Vec<Sender>>.

使用此结构,仅使用 insert()在需要更改这样的值时会变得笨拙,但是可以使用 Entry API进行检索和更新一口气记录。例如:

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. 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); 




您也可以使用 multimap 板条箱,其功能与之相似,但增加了一层抽象层。您可能会发现使用它更容易:


You could also use the multimap crate, which does something similar under the hood, but adds a layer of abstraction. 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);

方法 multi_map.get(key)将是第一个值使用该键,而 multi_map.get_vec(key)将检索所有这些键。

The method multi_map.get(key) will the first value with that key, while multi_map.get_vec(key) will retrieve all of them.

这篇关于如何在同一个密钥的Rust HashMap中存储多个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆