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

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

    You can use std::any::type_name. The following are examples of primitive data types which are capiable without &.

    use std::any::type_name;
    
    fn type_of(_: T) -> &'static str {
        type_name::()
    }
    
    fn main() {
        let str1 = "Rust language";
        let str2 = str1;
        println!("str1 is:  {}, and the type is {}.", str1, type_of(str1));
        println!("str2 is: {}, and the type is {}.", str2, type_of(str2));
        let bool1 = true;
        let bool2 = bool1;
        println!("bool1 is {}, and the type is {}.", bool1, type_of(bool1));
        println!("bool2 is {}, and the type is {}.", bool2, type_of(bool2));
        let x1 = 5;
        let x2 = x1;
        println!("x1 is {}, and the type is {}.", x1, type_of(x1));
        println!("x2 is {}, and the type is {}.", x2, type_of(x2));
        let a1 = 'a';
        let a2 = a1;
        println!("a1 is {}, and the type is {}.", a1, type_of(a1));
        println!("a2 is {}, and the type is {}.", a2, type_of(a2));
        let tup1= ("hello", 5, 'c');
        let tup2 = tup1;
        println!("tup1 is {:?}, and the type is {}.", tup1, type_of(tup1));
        println!("tup2 is {:?}, and the type is {}.", tup2, type_of(tup2));
        let array1: [i32; 3] = [0; 3];
        let array2 = array1;
        println!("array1 is {:?}, and the type is {}.", array1, type_of(array1));
        println!("array2 is {:?}, and the type is {}.", array2, type_of(array2));
        let array: [i32; 5] = [0, 1, 2, 3, 4];
        let slice1 = &array[0..3];
        let slice2 = slice1;
        println!("slice1 is {:?}, and the type is {}.", slice1, type_of(slice1));
        println!("slice2 is {:?}, and the type is {}.", slice2, type_of(slice2));
    }
    

    The output is

    str1 is:  Rust language, and the type is &str.
    str2 is: Rust language, and the type is &str.
    bool1 is true, and the type is bool.
    bool2 is true, and the type is bool.
    x1 is 5, and the type is i32.
    x2 is 5, and the type is i32.
    a1 is a, and the type is char.
    a2 is a, and the type is char.
    tup1 is ("hello", 5, 'c'), and the type is (&str, i32, char).
    tup2 is ("hello", 5, 'c'), and the type is (&str, i32, char).
    array1 is [0, 0, 0], and the type is [i32; 3].
    array2 is [0, 0, 0], and the type is [i32; 3].
    slice1 is [0, 1, 2], and the type is &[i32].
    slice2 is [0, 1, 2], and the type is &[i32].
    

提交回复
热议问题