What is the {integer} or {float} in a compiler error message?

后端 未结 2 1089
南笙
南笙 2020-12-06 17:49

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 l

相关标签:
2条回答
  • 2020-12-06 18:10

    {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}.

    0 讨论(0)
  • 2020-12-06 18:28

    {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.

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