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
The other answers show you how to accept an iterator, but gloss over answering your actual question:
Why can't I use
&Iterator
as an iterator?
Amusingly enough, you've prevented it yourself:
and I certainly don't want to mutate the passed argument
Iterators work by mutating their target — that's how the iterator can change to return a new value for each call!
pub trait Iterator {
type Item;
fn next(&mut self) -> Option;
// ^^^
}
By taking in an immutable trait object, it's impossible for your iterator to update itself, thus it's impossible to actually iterate.
The absolute smallest thing you can do to make your code compile is to accept a mutable reference:
fn max_width(strings: &mut dyn Iterator- ) -> usize
However, I'd probably write the function as:
fn max_width(strings: I) -> usize
where
I: IntoIterator,
I::Item: AsRef,
{
strings
.into_iter()
.map(|s| s.as_ref().len())
.max()
.unwrap_or(0)
}
return