返回Iterator(或任何其他特性)的正确方法是什么?

返回Iterator(或任何其他特性)的正确方法是什么?

下面的RUST代码编译并运行,没有任何问题。

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

在那之后,我尝试过这样的.但它没有编译

fn main() {
    let text = "word1 word2 word3";
    println!("{}", to_words(text).take(2).count());}fn to_words(text: &str) -> &Iterator<Item = &str> {
    &(text.split(' '))}

主要问题是我不确定函数的返回类型是什么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>> : std::iter::Iterator`

什么才是正确的代码使这个运行?.我的知识差距在哪里?


胡子哥哥
浏览 680回答 3
3回答
打开App,查看更多内容
随时随地看视频慕课网APP