从 HashMap 中获取第一个元素 [英] Get first element from HashMap

查看:189
本文介绍了从 HashMap 中获取第一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个HashMap,需要获取第一个元素:

I have a HashMap and need to get the first element:

type VarIdx = std::collections::HashMap<u16, u8>;

fn get_first_elem(idx: VarIdx) -> u16 {
    let it = idx.iter();
    let ret = match it.next() {
        Some(x) => x,
        None => -1,
    };
    ret
}

fn main() {}

但代码无法编译:

error[E0308]: match arms have incompatible types
 --> src/main.rs:5:15
  |
5 |       let ret = match it.next() {
  |  _______________^
6 | |         Some(x) => x,
7 | |         None => -1,
8 | |     };
  | |_____^ expected tuple, found integral variable
  |
  = note: expected type `(&u16, &u8)`
             found type `{integer}`
note: match arm with an incompatible type
 --> src/main.rs:7:17
  |
7 |         None => -1,
  |                 ^^

我该如何解决?

推荐答案

没有第一"之类的东西.HashMap 中的项目.不保证顺序值的存储位置以及迭代它们的顺序.

There is no such thing as the "first" item in a HashMap. There are no guarantees about the order in which the values are stored nor the order in which you will iterate over them.

如果顺序很重要,那么也许您可以切换到 BTreeMap,根据键保持顺序.

If order is important then perhaps you can switch to a BTreeMap, which preserves order based on the keys.

如果您只需要获取遇到的第一个值,换句话说,任何值,您可以执行与原始代码类似的操作:创建一个迭代器,只取第一个值:

If you just need to get the first value that you come across, in other words any value, you can do something similar to your original code: create an iterator, just taking the first value:

fn get_first_elem(idx: VarIdx) -> i16 {
    match idx.values().next() {
        Some(&x) => x as i16,
        None => -1,
    }
}

values() 方法仅在值上创建一个迭代器.您的错误的原因是 iter() 将在键和值对上创建一个迭代器,这就是您收到错误 expected tuple" 的原因.

The method values() creates an iterator over just the values. The reason for your error is that iter() will create an iterator over pairs of keys and values which is why you got the error "expected tuple".

为了让它编译,我不得不改变一些其他的东西:-1 不是一个有效的 u16 值,所以必须变成 i16,你的值是 u8 所以必须转换成 i16.

To make it compile, I had to change a couple of other things: -1 is not a valid u16 value so that had to become i16, and your values are u8 so had to be cast to i16.

作为另一个一般性评论,返回 -1 表示失败并不是很生锈".这就是 Option 的用途,鉴于 next() 已经返回了一个 Option,这很容易实现:

As another general commentary, returning -1 to indicate failure is not very "Rusty". This is what Option is for and, given that next() already returns an Option, this is very easy to accomplish:

fn get_first_elem(idx: VarIdx) -> Option<u8> {
    idx.values().copied().next()
}

.copied() 用于将迭代器的 &u8 值转换为 u8.

The .copied() is needed in order to convert the &u8 values of the iterator into u8.

这篇关于从 HashMap 中获取第一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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