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

相关推荐
Brain 博览记38 分钟前
脑网络AI丨给图神经网络装上“信息高速路”
开发语言·网络·论文阅读·人工智能·深度学习·神经网络·机器学习
Java码农也是农44 分钟前
Rust、Java、Python、C++ 有什么区别?从 CPU 执行到内存管理
java·python·rust
郝学胜-神的一滴1 小时前
Effective Python 条款44:善用属性注解
开发语言·c++·vscode·python·算法·stl
可夫小子5 小时前
AI 写了 200 万行 Rust 克隆闭源二进制分析软件,软件保护的旧防线还稳吗
rust
两点王爷13 小时前
Java 面试高频:JWT、Cookie、Session、Token 鉴权详解
java·开发语言·面试
微笑星河q15 小时前
C++高阶之【多态】
开发语言·c++
ClkLog-开源埋点用户分析18 小时前
【产品说明】【埋点分析】ClkLog 商业版 Java 运行环境安全更新说明
java·开发语言
yuzhiboyouye19 小时前
《阿里巴巴 Java 开发手册》的 MySQL 核心规范
java·开发语言·mysql
郝学胜-神的一滴19 小时前
Effective STL 条款12:对容器线程安全性的现实期望
c语言·开发语言·c++·qt·网络协议·rpc·numpy