How to write a Rust function that takes an iterator?

后端 未结 3 2026
遇见更好的自我
遇见更好的自我 2020-11-27 20:57

I\'d like to write a function that accepts an iterator and returns the results of some operations on it. Specifically, I\'m trying to iterate over the values of a Has

3条回答
  •  [愿得一人]
    2020-11-27 21:10

    Easiest is using an impl Trait, impl Iterator:

    use std::collections::HashMap;
    
    fn find_min<'a>(vals: impl Iterator) -> 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()));
    }
    

    playground

提交回复
热议问题