以下 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`
正确的代码是什么?我在哪方面的知识存在空白?
type LibraryResult<T> = Result<T, LibraryError>
这样的类型别名作为方便,类似于IoResult<T>
,也只是一个类型别名。 - reemimpl
关键字和boxes之间的交互方式,以及哪种方法更受欢迎以及为什么。仍然不确定迭代器应该在堆栈上扎根的位置,以及这可能会影响哪些传递迭代器的方法是必要的。 - gnkdl_gansklgna