When are numeric literals assigned to default types?

前端 未结 1 1361

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         


        
1条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-21 06:30

    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.

    0 讨论(0)
提交回复
热议问题