简体   繁体   English

Rust 的类型推断如何跨多个语句工作?

[英]How does Rust's type inference work across multiple statements?

Rust performs type inference in fairly advanced situations. Rust 在相当高级的情况下执行类型推断。 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 uses Hindley-Milner type system. Rust 使用Hindley-Milner类型系统。 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:可以在那里找到它的正式描述和解释:

"What part of Hindley-Milner do you not understand?" “你不明白欣德利-米尔纳的哪一部分?”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM