以下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的新手,来自C#/ Java /类似.
在C#中,我们IEnumerable<T>可以使用它来迭代几乎任何类型的数组或列表.C#还有一个yield关键字,可用于返回惰性列表.这是一个例子......
// Lazily returns the even numbers out of an enumerable
IEnumerable<int> Evens(IEnumerable<int> input)
{
foreach (var x in input)
{
if (x % 2 == 0)
{
yield return x;
}
}
}
Run Code Online (Sandbox Code Playgroud)
这当然是一个愚蠢的例子.我知道我可以用Rust的map函数做到这一点,但我想知道如何创建自己的接受和返回泛型迭代器的方法.
从我可以收集到的内容,Rust具有可以类似使用的泛型迭代器,但它们超出了我的理解.我看到Iter,IntoIterator,Iterator类型,以及可能更多的文档,但没有很好地理解他们.
任何人都可以提供如何创建上述内容的明确示例吗?谢谢!
PS懒惰的方面是可选的.我更关心远离特定列表和数组类型的抽象.