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
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