在 rust 中没有类似于 typeof 的操作符来判断一个变量的类型,但是我们可以自己写一个函数来打印变量的类型。
use std::any::type_name;
fn test_type<T>(_: T) {
println!("{:?}", { type_name::<T>() });
}
用法实例如下:
let tup: (i32, f64, u8, bool, &str) = (500, 3.2, 1, false, "Hello World");
println!("{:?}", tup);
println!("{} {}", tup.0, tup.4);
// typeof
test_type(tup); // "(i32, f64, u8, bool, &str)"
test_type(tup.4); // "&str"
let arr: [i32; 5] = [1, 2, 3, 4, 5];
let months: [&str; 3] = ["Jan", "Feb", "Mar"];
test_type(arr); // "[i32; 5]"
test_type(months); // "[&str; 3]"