两种写法
1. 直接打印
fn print_type_of<T>(_: &T) { println!( "{}", std::any::type_name::<T>() ); } 或者 fn print_type_of<T>(_: T) { println!("{}", std::any::type_name::<T>()); } 上面那种,传 引用, 下面这种,直接传值, 会转移所有权
2. 返回字符串
fn type_of<T>(_: T) -> &'static str {
std::any::type_name::<T>()
} 或者 fn type_of<T>(_: &T) -> &'static str { std::any::type_name::<T>() } 也是 转移所有权的区别 调用示范: println!("{}", type_of(&x));
3.其他方法 (新功能https://github.com/rust-lang/rust/issues/66359)
use std::any::type_name_of_val; let x = 1; println!("{}", type_name_of_val(&x));
4.基本类型:
1)整数:
u8, i8, u16, i16, u32, i32, u64, i64, u128, i128
2)浮点数:
f32, f64
3)逻辑数(布尔类型)
true, false
4)字符 (char)
let alphabet:char = 'A'; let emoji:char = '😁';
5)数组 array
6) 元组 tuple
5. 完整代码
fn type_of(_: &T) -> &'static str { std::any::type_name::() } fn main() { let buff = [0x21 as u8, 0x22, 0x23, 0x24]; println!("{}", type_of(&buff)); }
运行结果:
[u8; 4]
6. 得到占用空间的大小
fn main() { fn size_of_val<T>(_: &T) -> usize { std::mem::size_of::<T>() } let arr = [0u8; 4]; println!("size_of arr: {}", size_of_val(&arr)); }
7. 图示