[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?

相关推荐
CRMEB定制开发1 小时前
2026年最值得推荐的10大开源商城系统盘点
开发语言·人工智能·开源·商城系统·小程序商城
buhuizhiyuci1 小时前
【QT-百日筑基篇】修真世界摸爬滚打多年,终于黄天不负有心人,突破炼器中期——常用控件QWight的属性
开发语言·c++·qt·gui·图形化
Littlehero_1213 小时前
QT自定义控件之热换站系统(源码开源)
开发语言·qt
meilindehuzi_a3 小时前
Python 基础语法(1):常量、变量、类型、输入输出与运算符
开发语言·python
caimouse3 小时前
ReactOS 窗口系统分析(5):可见区域与窗口 DC — vis.c + windc.c
c语言·开发语言
OPEN-F3 小时前
Python进阶教程:装饰器与生成器深入
开发语言·python
千里码aicood4 小时前
基于Python的电商数据采集系统(大数据+爬虫)
开发语言·python
小灰灰搞电子4 小时前
Rust+Slint 实现动态加载效果源码分享
rust·slint·等待控件
福大大架构师每日一题5 小时前
ragflow v0.27.0 发布:Go 后端全面对齐、智能体搜索与知识编译大升级,超全更新解析
开发语言·后端·golang
陈皮波比茶5 小时前
Python项目实战-网络机器人(爬虫)
开发语言·网络·爬虫·python·机器人