【发布时间】:2016-04-30 10:08:28
【问题描述】:
我想写一个函数,它接受一个迭代器并返回一些操作的结果。具体来说,我正在尝试遍历 HashMap 的值:
use std::collections::HashMap;
fn find_min<'a>(vals: Iterator<Item=&'a u32>) -> Option<&'a u32> {
vals.min()
}
fn main() {
let mut map = HashMap::new();
map.insert("zero", 0u32);
map.insert("one", 1u32);
println!("Min value {:?}", find_min(map.values()));
}
可惜:
error: the `min` method cannot be invoked on a trait object
--> src/main.rs:4:10
|
4 | vals.min()
| ^^^
error[E0277]: the trait bound `std::iter::Iterator<Item=&'a u32> + 'static: std::marker::Sized` is not satisfied
--> src/main.rs:3:17
|
3 | fn find_min<'a>(vals: Iterator<Item = &'a u32>) -> Option<&'a u32> {
| ^^^^ `std::iter::Iterator<Item=&'a u32> + 'static` does not have a constant size known at compile-time
|
= help: the trait `std::marker::Sized` is not implemented for `std::iter::Iterator<Item=&'a u32> + 'static`
= note: all local variables must have a statically known size
error[E0308]: mismatched types
--> src/main.rs:11:41
|
11 | println!("Min value {:?}", find_min(map.values()));
| ^^^^^^^^^^^^ expected trait std::iter::Iterator, found struct `std::collections::hash_map::Values`
|
= note: expected type `std::iter::Iterator<Item=&u32> + 'static`
found type `std::collections::hash_map::Values<'_, &str, u32>`
如果我尝试通过引用传递,我会得到同样的错误;如果我使用Box,我会得到终身错误。
【问题讨论】:
-
许多用例会受益于提出一个更广泛的问题:“如何编写一个采用 iterable 的 Rust 函数?”可迭代,我的意思是可以迭代的东西。 (这比迭代器更广泛。)正如in this answer 所述,要做到这一点,请使用
IntoIterator,因为任何实现IntoIterator的类型都是可迭代的。