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

问题描述 投票:0回答:1

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

示例(游乐场):

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>) {}
  • 为什么有些闭包推断参数类型而其他闭包需要注释?

  • 是否有可能重新设计 trait 或 function 以不再需要注释?

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

  1. bar
    需要
    Foo<bool, Output = bool>
  2. 只有
    Fn(bool) -> bool
    实现
    Foo<bool, Output = bool>
  3. 闭包一定要
    |bool| -> bool

否定(

Not
特征)将输入类型与输出类型分离的事实应该无关紧要,但它似乎在某种程度上是一个关键因素。

generics rust closures traits
1个回答
0
投票

这似乎是一个小故障。 Rust-analyzer LSP 能够推断出类型应该是什么,但无论出于何种原因,编译器都不能。

据我所知,这段代码不能在任何版本的 Rust 上编译,也不能用

cargo fix
自动修复。

有趣的是,编译器does似乎在这个等效代码上工作:

bar(|x| x ^ true);
© www.soinside.com 2019 - 2024. All rights reserved.