相关疑难解决方法(0)

返回迭代器(或任何其他特征)的正确方法是什么?

以下Rust代码编译并运行没有任何问题.

fn main() {
    let text = "abc";
    println!("{}", text.split(' ').take(2).count());
}
Run Code Online (Sandbox Code Playgroud)

在那之后,我尝试了类似的东西....但它没有编译

fn main() {
    let text = "word1 word2 word3";
    println!("{}", to_words(text).take(2).count());
}

fn to_words(text: &str) -> &Iterator<Item = &str> {
    &(text.split(' '))
}
Run Code Online (Sandbox Code Playgroud)

主要问题是我不确定函数to_words()应该具有什么返回类型.编译器说:

error[E0599]: no method named `count` found for type `std::iter::Take<std::iter::Iterator<Item=&str>>` in the current scope
 --> src/main.rs:3:43
  |
3 |     println!("{}", to_words(text).take(2).count());
  |                                           ^^^^^
  |
  = note: the method `count` exists but the following trait bounds were not satisfied:
          `std::iter::Iterator<Item=&str> : std::marker::Sized`
          `std::iter::Take<std::iter::Iterator<Item=&str>> …
Run Code Online (Sandbox Code Playgroud)

rust

92
推荐指数
1
解决办法
2万
查看次数

标签 统计

rust ×1