Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
978 views
in Technique[技术] by (71.8m points)

rust - When are numeric literals assigned to default types?

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 `()`

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?

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

expected integral variable, found ()

= note: expected type `{integer}`
= note:    found type `()`
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...