【发布时间】:2017-12-24 22:35:30
【问题描述】:
我有一个HashMap,需要获取第一个元素:
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::iter有一个 tiny 数量的文档来解释您的所有问题:“一个迭代器以任意顺序访问所有键值对。迭代器元素类型是(&'a K, &'a V)。”