How to get the data type of a variable in Rust

1 Answer

0 votes
fn print_type_of<T>(_: &T) {
    println!("{}", std::any::type_name::<T>());
}

fn main() {
    let x = 42;
    let s = "Hello, Rust!";
    
    print_type_of(&x); // Prints: i32 (or i64 depending on platform/inference)
    print_type_of(&s); // Prints: &str
}


/*
run:

i32
&str

*/

 



answered 11 hours ago by avibootz
...