Rust 中闭包和函数的类型推断差异 [英] Differences in Type inference for closures and functions in rust

查看:58
本文介绍了Rust 中闭包和函数的类型推断差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么可以推断闭包表达式的参数类型和返回类型,而不能推断 rust 中的函数?

Why is it possible to infer the types of arguments and return type for a closure expression while not for a function in rust?

推荐答案

这只是一个设计决定:Rust 使用局部类型推断,而不是全局类型推断.理论上可以进行全局类型推断,但为了便于调试,Rust 有意识地避开了它,因为它会导致极难调试的编译问题(例如,这部分的微小变化会导致内部深处的编译错误).

This is simply a design decision: Rust employs local type inference, but not global type inference. It is theoretically possible to do global type inference, but for ease of debugging Rust has consciously eschewed it, for it can lead to extremely difficult-to-debug compilation issues (e.g. a minor change in this part causes a compilation error deep in the internals).

函数是全局的——因此它们的类型签名必须是显式的.

Functions are global—their type signatures must thus be explicit.

函数内部的闭包是局部的——它们的类型可以被推断出来.(当然,如果您将闭包存储在结构体中,则需要在结构体的类型定义中明确指定其类型.)

Closures, being inside a function, are local—their types can be inferred. (Of course, if you are storing a closure in a struct, its type will need to be explicitly specified in the struct’s type definition.)

这篇关于Rust 中闭包和函数的类型推断差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆