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

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

    You can use the std::any::type_name function. This doesn't need a nightly compiler or an external crate, and the results are quite correct:

    fn print_type_of(_: &T) {
        println!("{}", std::any::type_name::())
    }
    
    fn main() {
        let s = "Hello";
        let i = 42;
    
        print_type_of(&s); // &str
        print_type_of(&i); // i32
        print_type_of(&main); // playground::main
        print_type_of(&print_type_of::); // playground::print_type_of
        print_type_of(&{ || "Hi!" }); // playground::main::{{closure}}
    }
    

    Be warned: as said in the documentation, this information must be used for a debug purpose only:

    This is intended for diagnostic use. The exact contents and format of the string are not specified, other than being a best-effort description of the type.

    If you want your type representation to stay the same between compiler versions, you should use a trait, like in the phicr's answer.

提交回复
热议问题