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.
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,
}
}
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".
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
.
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()
}
The .copied()
is needed in order to convert the &u8
values of the iterator into u8
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…