我正在编写一个接受不同特征实现器的函数。其中之一是闭包。有些闭包需要一个参数类型注释,而有些则不需要,具体取决于它们的主体。
示例(playground):
fn main() {
bar(|x| x);
bar(|x: bool| !x); // Why is the annotation needed?
}
trait Foo<T> {
type Output;
}
impl<F: Fn(T) -> O, T, O> Foo<T> for F {
type Output = O;
}
fn bar(_: impl Foo<bool, Output = bool>) {}
为什么某些闭包可以推断参数类型,而另一些则需要注释?
是否可以重新设计特征或功能以不再需要注释?
我的(无效的)推理是两个闭包的推论是相同的:
bar
需要Foo<bool, Output = bool>
Fn(bool) -> bool
实现Foo<bool, Output = bool>
|bool| -> bool
否定(Not
特征)使输入类型与输出类型分离的事实无关紧要,但这似乎是一个至关重要的因素。