How to write a Rust function that takes an iterator?

后端 未结 3 2033
遇见更好的自我
遇见更好的自我 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:12

    You want to use generics here:

    fn find_min<'a, I>(vals: I) -> Option<&'a u32>
    where
        I: Iterator,
    {
        vals.min()
    }
    

    Traits can be used in two ways: as bounds on type parameters and as trait objects. The book The Rust Programming Language has a chapter on traits and a chapter on trait objects that explain these two use cases.

    Additionally, you often want to take something that implements IntoIterator as this can make the code calling your function nicer:

    fn find_min<'a, I>(vals: I) -> Option<&'a u32>
    where
        I: IntoIterator,
    {
        vals.into_iter().min()
    }
    

提交回复
热议问题