【发布时间】:2018-08-09 20:37:08
【问题描述】:
在给定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(不带分号)。
标签: rust