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

后端 未结 11 2149
无人共我
无人共我 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:12

    There's a @ChrisMorgan answer to get approximate type ("float") in stable rust and there's a @ShubhamJain answer to get precise type ("f64") through unstable function in nightly rust.

    Now here's a way one can get precise type (ie decide between f32 and f64) in stable rust:

    fn main() {
        let a = 5.;
        let _: () = unsafe { std::mem::transmute(a) };
    }
    

    results in

    error[E0512]: cannot transmute between types of different sizes, or dependently-sized types
     --> main.rs:3:27
      |
    3 |     let _: () = unsafe { std::mem::transmute(a) };
      |                           ^^^^^^^^^^^^^^^^^^^
      |
      = note: source type: `f64` (64 bits)
      = note: target type: `()` (0 bits)
    

    Update

    The turbofish variation

    fn main() {
        let a = 5.;
        unsafe { std::mem::transmute::<_, ()>(a) }
    }
    

    is slightly shorter but somewhat less readable.

提交回复
热议问题