How can I store multiple elements in a Rust HashMap for the same key?

后端 未结 1 1374
囚心锁ツ
囚心锁ツ 2021-01-18 21:44

I have a HashMap. Sender is a open connection object and the key is a user id. Each user can connect from multiple devices. I ne

相关标签:
1条回答
  • 2021-01-18 22:14

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

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

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

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

    0 讨论(0)
提交回复
热议问题