What is the {integer} or {float} in a compiler err

2020-02-01 19:00发布

问题:

It is surprisingly hard to find this in the docs. This might even be a two part question:

  1. Are {integer} and {float} some sort of language alias for a specific primitive type?

  2. What does it mean for a type name to be enclosed in curly braces in a compilation/syntax error message?

Example:

error: no method named pow found for type {integer} in the current scope

回答1:

{integer} is an integral value whose concrete type was not specified and has not been inferred by the compiler yet; the following code:

fn main() {
    let x = 1;
    let () = x;
}

Will result in the following error:

error[E0308]: mismatched types

 --> <anon>:3:9
  |
3 |     let () = x;
  |         ^^ expected integral variable, found ()
  |
  = note: expected type `{integer}`
  = note:    found type `()`

The same would happen with a floating number:

fn main() {
    let x = 1.0;
    let () = x;
}
error[E0308]: mismatched types
 --> <anon>:3:9
  |
3 |     let () = x;
  |         ^^ expected floating-point variable, found ()
  |
  = note: expected type `{float}`
  = note:    found type `()`

Because the compilation error caused by the invalid assignment let () = x is thrown before the type inference can happen.

In other words, until the compilation reaches the type inference stage where an integer or a float without a concrete type specified would be recognized (e.g. based on function application) or assigned the default type, i32 for integers and f64 for floats, compilation errors will refer to it as an {integer} or a {float}.



回答2:

{integer} in error messages is a placeholder for any of the integer types ({i,u}{8,16,32,64,128}). (Source)

Integer literals in Rust are type inferred based on their usage. For example, in the following code, the type of 123 is u8 in the first instance and u64 in the second:

let a: u8 = 123;
let a: u64 = 123;

{integer} is used to represent any integer type in error messages when the compiler hasn't figured out a concrete type of the value.