Why can't I use `&Iterator` as an iterator?

前端 未结 3 2117
心在旅途
心在旅途 2021-01-04 13:29

I have the following function that\'s supposed to find and return the longest length of a String given an Iterator:

fn max_width(st         


        
3条回答
  •  鱼传尺愫
    2021-01-04 14:23

    Your code fails because Iterator is not the same as &Iterator. You can fix this if you pass Iterator to your function, but since Iterator is a trait, the size cannot be determined (You can't know, what Iterator you are passing). The solution is to pass anything that implements Iterator:

    fn max_width<'a>(strings: impl Iterator) -> usize
    

    playground


    For more experienced Rust users:

    The most generic way is probably this:

    fn max_width>(strings: impl IntoIterator) -> usize {
        let mut max_width = 0;
        for string in strings {
            let string = string.as_ref();
            if string.len() > max_width {
                max_width = string.len();
            }
        }
        max_width
    }
    

    playground

    However, you can also use

    fn max_width>(strings: impl IntoIterator) -> usize {
        strings
            .into_iter()
            .map(|s| s.as_ref().len())
            .max()
            .unwrap_or(0)
    }
    

    playground

提交回复
热议问题