How do I print the type of a variable in Rust?

后端 未结 11 2233
无人共我
无人共我 2020-11-22 08:49

I have the following:

let mut my_number = 32.90;

How do I print the type of my_number?

Using type and

11条回答
  •  春和景丽
    2020-11-22 09:14

    If you merely wish to find out the type of a variable and are willing to do it at compile time, you can cause an error and get the compiler to pick it up.

    For example, set the variable to a type which doesn't work:

    let mut my_number: () = 32.90;
    // let () = x; would work too
    
    error[E0308]: mismatched types
     --> src/main.rs:2:29
      |
    2 |     let mut my_number: () = 32.90;
      |                             ^^^^^ expected (), found floating-point number
      |
      = note: expected type `()`
                 found type `{float}`
    

    Or call an invalid method:

    let mut my_number = 32.90;
    my_number.what_is_this();
    
    error[E0599]: no method named `what_is_this` found for type `{float}` in the current scope
     --> src/main.rs:3:15
      |
    3 |     my_number.what_is_this();
      |               ^^^^^^^^^^^^
    

    Or access an invalid field:

    let mut my_number = 32.90;
    my_number.what_is_this
    
    error[E0610]: `{float}` is a primitive type and therefore doesn't have fields
     --> src/main.rs:3:15
      |
    3 |     my_number.what_is_this
      |               ^^^^^^^^^^^^
    

    These reveal the type, which in this case is actually not fully resolved. It’s called “floating-point variable” in the first example, and “{float}” in all three examples; this is a partially resolved type which could end up f32 or f64, depending on how you use it. “{float}” is not a legal type name, it’s a placeholder meaning “I’m not completely sure what this is”, but it is a floating-point number. In the case of floating-point variables, if you don't constrain it, it will default to f64¹. (An unqualified integer literal will default to i32.)

    See also:

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

    ¹ There may still be ways of baffling the compiler so that it can’t decide between f32 and f64; I’m not sure. It used to be as simple as 32.90.eq(&32.90), but that treats both as f64 now and chugs along happily, so I don’t know.

提交回复
热议问题