我有以下函数,它应该能够从一个Iterator
中找到并返回最长的String
长度:
fn max_width(strings: &Iterator<Item = &String>) -> usize {
let mut max_width = 0;
for string in strings {
if string.len() > max_width {
max_width = string.len();
}
}
return max_width;
}
然而,编译器给了我以下错误:
error[E0277]: the trait bound `&std::iter::Iterator<Item=&std::string::String>: std::iter::Iterator` is not satisfied
--> src/main.rs:3:19
|
3 | for string in strings {
| ^^^^^^^ `&std::iter::Iterator<Item=&std::string::String>` is not an iterator; maybe try calling `.iter()` or a similar method
|
= help: the trait `std::iter::Iterator` is not implemented for `&std::iter::Iterator<Item=&std::string::String>`
= note: required by `std::iter::IntoIterator::into_iter`
我刚接触Rust,并对此感到非常困惑,因为我认为我已经显式传递了一个迭代器。调用strings.iter()
告诉我它没有实现,而调用strings.into_iter()
会让我陷入可变性的困境,我肯定不想改变传递的参数。
我该如何遍历我的字符串?
return
关键字。只需写max_width
(不加分号)。 - Tim Diekmann