How can I print the type of a variable?


#1
fn main() {
    let x = 3;
    let y = 2.3;
    //how to print types of x, y.
    //i32, f32..
    println!("");
}

#2

You don’t.

The closest would be a type’s TypeId, but even then you need to already know what the type is, and it looks like this:

fn main() {
    println!("{:?}", std::any::TypeId::of::<i32>());
}
TypeId { t: 10645063183773766558 }

If what you’re actually trying to do is fine out what the type of an expression is, you can always ask the compiler by introducing a deliberate type mismatch:

fn main() {
    let _: () = 42;
}
<anon>:2:17: 2:19 error: mismatched types:
 expected `()`,
    found `_`
(expected (),
    found integral variable) [E0308]
<anon>:2     let _: () = 42;
                         ^~
<anon>:2:17: 2:19 help: see the detailed explanation for E0308

#3

You can use TypeId without knowing the type:

fn typeid<T: std::any::Any>(_: &T) {
    println!("{:?}", std::any::TypeId::of::<T>());
}

struct Foo;
struct Bar;

fn main() {
    let f = Foo;
    typeid(&f);
    let b = Bar;
    typeid(&b);
    
    let x = 5;
    typeid(&x);
    println!("{:?}", std::any::TypeId::of::<i32>());
    
    let y = 5.;
    typeid(&y);
    println!("{:?}", std::any::TypeId::of::<f64>());
}

#4

Thanks for help!