Types 从未包含泛型参数的函数返回泛型类型
我目前正在尝试用Rust编写一个小函数,它返回一个迭代器,遍历一个简单的LISP风格计算器语言的标记。我没想到会遇到编译错误 我第一次尝试编写函数是:Types 从未包含泛型参数的函数返回泛型类型,types,rust,type-inference,Types,Rust,Type Inference,我目前正在尝试用Rust编写一个小函数,它返回一个迭代器,遍历一个简单的LISP风格计算器语言的标记。我没想到会遇到编译错误 我第一次尝试编写函数是: fn标记器\u对于Peekable where I:Iterator在Rust中,当您在项列表中指定了生存期或类型参数时,这些生存期或类型参数将在使用站点选择 此函数签名表示函数的调用方可以选择I的类型: fn标记器\u用于可查看的位置I:Iterator) 另一方面,这个签名表示返回类型仅仅是实现迭代器>的东西: fn标记器\u用于(s:&st
fn标记器\u对于Peekable where I:Iterator在Rust中,当您在项
列表中指定了生存期或类型参数时,这些生存期或类型参数将在使用站点选择
此函数签名表示函数的调用方可以选择I
的类型:
fn标记器\u用于可查看的位置I:Iterator
)
另一方面,这个签名表示返回类型仅仅是实现迭代器>
的东西:
fn标记器\u用于(s:&str)->可查看;
调用方无法选择该类型;编译器从函数体推断实际类型。在Rust中,如果在项列表中指定了生存期或类型参数,则这些生存期或类型参数将在使用站点选择
此函数签名表示函数的调用方可以选择I
的类型:
fn标记器\u用于可查看的位置I:Iterator
)
另一方面,这个签名表示返回类型仅仅是实现迭代器>
的东西:
fn标记器\u用于(s:&str)->可查看;
调用方无法选择该类型;编译器从函数体推断实际类型
error[E0308]: mismatched types
--> src/lib.rs:4:5
|
3 | fn tokenizer_for<'a, I>(s: &'a str) -> Peekable<I> where I: Iterator<Item=&'a str> {
| - ----------- expected `std::iter::Peekable<I>` because of return type
| |
| this type parameter
4 | / s.split_whitespace()
5 | | .flat_map(
6 | | |word| {
7 | | word.replace("(", "( ").replace(")", " )").split_whitespace()
8 | | }
9 | | )
10 | | .peekable()
| |___________________^ expected type parameter `I`, found struct `std::iter::FlatMap`
|
= note: expected struct `std::iter::Peekable<I>`
found struct `std::iter::Peekable<std::iter::FlatMap<std::str::SplitWhitespace<'_>, std::str::SplitWhitespace<'_>, [closure@src/lib.rs:6:13: 8:14]>>`
= help: type parameters must be constrained to match other types
= note: for more information, visit https://doc.rust-lang.org/book/ch10-02-traits.html#traits-as-parameters