Cod*_*ich 10 generics closures traits rust
我正在编写一个接受不同特征实现者的函数.其中一个是关闭.有些闭包需要参数类型注释,有些则不需要,具体取决于它们的主体.
示例(游乐场):
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>) {}
Run Code Online (Sandbox Code Playgroud)
为什么有些闭包会推断出参数类型而其他闭包需要注释?
是否有可能重新设计特征或功能从不需要注释?
我的(无效)推理是两个闭包的推理是相同的:
bar 需求 Foo<bool, Output = bool>Fn(bool) -> bool工具Foo<bool, Output = bool>|bool| -> bool否定(Nottrait)将输入类型与输出类型分离的事实应该无关紧要,但它似乎在某种程度上是一个关键因素.
小智 1
这似乎是一个小故障。Rust 分析器 LSP 能够推断出应该是什么类型,但无论出于何种原因,编译器都无法推断出类型。
据我所知,这段代码不能在任何版本的 Rust 上编译,并且不能使用cargo fix.
有趣的是,编译器似乎确实可以处理以下等效代码:
bar(|x| x ^ true);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
189 次 |
| 最近记录: |