Rust 的类型推断如何跨多个语句工作? [英] How does Rust's type inference work across multiple statements?

查看:30
本文介绍了Rust 的类型推断如何跨多个语句工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Rust 在相当高级的情况下执行类型推断.有人可以解释(或指出)描述可以推断和不能推断的规则吗?

Rust performs type inference in fairly advanced situations. Could someone please explain (or point to) the rules that describe what can and cannot be inferred?

第一个很简单:绑定的类型就是绑定表达式的类型:

The first one is simple: The type of a binding is the type of the bound expression:

let n = 10u32;

// Same as:
//   vvvvv
let n: u32 = 10u32;

下一个更让我惊讶的是:右边的泛型参数是从左边的绑定类型推导出来的:

This next one is more surprising to me: The generic parameter on the right is deduced from the binding type on the left:

let n: u32 = "10".parse().unwrap();

// same as:            vvvvvvv
let n: u32 = "10".parse::<u32>().unwrap();

这也适用于泛型类型的成员函数":

This also works for "member functions" of generic types:

let b = Box::new(10u32);

// same as:
//        vvvvv      vvvvvvv
let b: Box<u32> = Box::<u32>::new(10u32);

但最奇怪的是跨语句的类型推断:

But the strangest of all is type inference across statements:

let v = Vec::new();   // no type!
v.push(10u32);        // apparently v is Vec<u32>?!
// v.push(10i32);     // type error

类型推断和类型推导的规则是什么?

What are the rules for type inference and type deduction?

推荐答案

Rust 使用 Hindley-Milner 类型系统.它是一组根据使用情况建立表达式类型的规则.

Rust uses Hindley-Milner type system. It is a set of rules about establishing types of expressions based on their usage.

可以在那里找到它的正式描述和解释:

Formal description and explanation for it can be found there:

"你不了解 Hindley-Milner 的哪一部分明白吗?"

这篇关于Rust 的类型推断如何跨多个语句工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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