[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?](https://stackoverflow.com/questions/21747136/how-do-i-print-in-rust-the-type-of-a-variable)

相关推荐
杜小暑8 分钟前
字符串与相应函数(下)
c语言·开发语言·算法
搬砖工程师Cola1 小时前
<C#>详细介绍builder.Services.AddHttpContextAccessor();
开发语言·c#
云边有个稻草人2 小时前
思维与算法共舞:AIGC语言模型的艺术与科学
开发语言·算法·什么是语言模型?·多任务学习与多模态生成·客户服务与聊天机器人·自适应生成与定制化文本·预训练与微调
pzx_0012 小时前
【深度学习】自定义实现DataSet和DataLoader
开发语言·人工智能·python·深度学习·算法
HelloRevit7 小时前
Next.js 快速启动模板
开发语言·javascript·ecmascript
春生野草9 小时前
0413-多态、Object类方法、访问权限修饰符、装箱拆箱、128陷阱
java·开发语言
烁3479 小时前
每日一题(小白)暴力娱乐篇26
java·开发语言·算法·娱乐
周周记笔记9 小时前
探索R语言:在线学习资源汇总
开发语言·r语言
zuoming1209 小时前
c# 系列pdf转图片 各种处理3--net3.1到net8 PDFtoImage
开发语言·pdf·c#
FreeLikeTheWind.9 小时前
Qt问题之 告别软件因系统默认中文输入法导致错误退出的烦恼
开发语言·c++·windows·经验分享·qt