[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 分钟前
Easyx图形库应用(用lua开发图形界面)
开发语言·lua
ellis19709 分钟前
Lua协程coroutine库用法
开发语言·lua
Amos_Web16 分钟前
Rust实战教程--文件管理命令行工具
前端·rust·全栈
nwsuaf_huasir29 分钟前
matlab构造带通巴特沃斯滤波器进行滤波
开发语言·matlab
救救孩子把30 分钟前
从 JDK 8 到 JDK 23:HotSpot 垃圾回收器全景演进与深度剖析
java·开发语言·jvm·jdk
清辞8531 小时前
C++入门(底层知识C与C++的不同)
开发语言·c++·算法
fqbqrr1 小时前
2510C++,api设计原则,不除零
开发语言·c++
科比不来it1 小时前
Go语言数据竞争Data Race 问题怎么检测?怎么解决?
开发语言·c++·golang
biter down1 小时前
c语言14:字符指针
c语言·开发语言
光军oi2 小时前
JAVA全栈JVM篇————初识JVM
java·开发语言·jvm