[Rust] 打印变量类型

一、简介

本文介绍了如何在Rust中打印变量的类型。

二、代码

代码:

rust 复制代码
// 使用 print_type_of 函数打印变量类型
fn print_type_of<T>(_: &T) {
    println!("{}", std::any::type_name::<T>())
}

fn main() {
    let s = "Hello";
    let i = 42;

    print_type_of(&s); // &str
    print_type_of(&i); // i32
    print_type_of(&main); // playground::main
    print_type_of(&print_type_of::<i32>); // playground::print_type_of<i32>
    print_type_of(&{ || "Hi!" }); // playground::main::{{closure}}
}

运行结果:

复制代码
&str
i32
hello_world::main
hello_world::print_type_of<i32>
hello_world::main::{{closure}}

三、参考

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

相关推荐
wuyk5552 小时前
3.链表:用指针串联的动态数据结构
c语言·开发语言·数据结构·链表
苏灿烤鱼3 小时前
公司**不可计算,就自己做操作系统
rust·typescript·agent
weixin_383196473 小时前
java基础面试题@Autowired和@Resource区别
java·开发语言
言乐64 小时前
Python游戏水平测试辅助系统2
开发语言·windows·python·游戏·django
我不是疯子是傻子4 小时前
Qt 实时曲线卡顿优化:从QPainter到OpenGL的3级加速实战
开发语言·qt
zlinear数据采集卡4 小时前
D223 ADC数据处理流水线:从原始采样值到工程单位的完整转换链
开发语言·arm开发·嵌入式硬件·fpga开发·开源·c#
nnerddboy5 小时前
Rust教程04:引用、借用与切片
开发语言·后端·rust
jerryinwuhan5 小时前
《Python数据预处理》第四章
开发语言·python
长江&后浪5 小时前
防火墙的描述
开发语言·网络·php
观无5 小时前
若依EasyExcel实现单元格合并
开发语言·前端·javascript