闭包如何根据需要实现的特征来推断其类型?

时间:2019-02-28 15:34:04

标签: generics rust closures traits

我正在编写一个接受不同特征实现器的函数。其中之一是闭包。有些闭包需要一个参数类型注释,而有些则不需要,具体取决于它们的主体。

示例(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>) {}
  • 为什么某些闭包可以推断参数类型,而另一些则需要注释?

  • 是否可以重新设计特征或功能以不再需要注释?

我的(无效的)推理是两个闭包的推论是相同的:

  1. bar需要Foo<bool, Output = bool>
  2. Fn(bool) -> bool实现Foo<bool, Output = bool>
  3. 闭包必须为|bool| -> bool

否定(Not特征)使输入类型与输出类型分离的事实无关紧要,但这似乎是一个至关重要的因素。

0 个答案:

没有答案