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

前端 未结 3 2128
心在旅途
心在旅途 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:11

    If you don't specifically need the generality of iterating over any given iterator, a simpler way to write the function is to have your max_width function take a &[&str] (A slice of string slices) instead. You can use a slice in a for loop because Rust knows how to turn that into an iterator (it implements IntoIterator trait):

    fn max_width(strings: &[&str]) -> usize {
        let mut max_width = 0;
        for string in strings {
            if string.len() > max_width {
                max_width = string.len();
            }
        }
        return max_width;
    }
    
    fn main() {
        let strings = vec![
            "following",
            "function",
            "supposed",
            "return",
            "longest",
            "string",
            "length"
        ];
    
        let max_width = max_width(&strings);
    
        println!("Longest string had size {}", max_width);
    }
    
    // OUTPUT: Longest string had size 9
    

    Playground here

提交回复
热议问题