数字文字何时分配给默认类型? [英] When are numeric literals assigned to default types?

查看:39
本文介绍了数字文字何时分配给默认类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在玩一些代码并进行了以下观察:

I was playing around with some code and made the following observation:

let x = 1;
let () = x;

error: mismatched types [E0308]
note:  expected type `_`
note:     found type `()`

这显然失败了,但我期望错误指出预期的类型是 i32,而不是 _.我发现未指定类型的浮动文字也会发生同样的情况,例如1.0.

This obviously fails, but I was expecting the error to state that the expected type was i32, not _. I found out that the same happens with a floating literal of an unspecified type, e.g. 1.0.

为什么会这样?类型不应该已经被称为默认类型吗?

Why is it so? Shouldn't the type already be known as the default?

更新:从 Rust 1.12 开始,错误消息提供了更多信息:

Update: as of Rust 1.12, the error message is more informative:

expected integral variable, found ()

= note: expected type `{integer}`
= note:    found type `()`

推荐答案

Rust 不仅从初始化中进行类型推断,还从每次使用中进行类型推断.因此,它的类型检查器必须查看变​​量的每次使用来决定它是什么类型,并且需要随着它的进行推断和检查类型.

Rust does type inference not just from the initialization, but from every usage. Thus, its type checker has to look at every usage of a variable to decide what type it is, and needs to deduce and check types as it goes along.

这意味着 let () = x; 是同一过程的一部分.它是 x 的用法,因此必须检查以查看 x 的具体类型.在编译器仍在尝试推断 x 的类型的同时发现没有可能的类型可以匹配 () 的事实,因此没有选择默认值,因为默认值仅在编译器查看了 x 的所有用法并且没有发现任何内容时才使用.

This means that the let () = x; is part of the same process. It is a usage of x and thus must be checked to see what concrete type x could be. The fact that no possible type could match () is discovered at the same time that the compiler is still trying to deduce the type of x, and so no default has been chosen, as the default is only used when the compiler has looked at all usages of x and not found anything.

这篇关于数字文字何时分配给默认类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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