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

相关推荐
tjl521314_2112 分钟前
04C++ 名称空间(Namespace)
开发语言·c++
赏金术士22 分钟前
Kotlin 数据流与单双向绑定
android·开发语言·kotlin
逻辑驱动的ken1 小时前
Java高频面试场景题25
java·开发语言·深度学习·面试·职场和发展
AI人工智能+电脑小能手2 小时前
【大白话说Java面试题】【Java基础篇】第32题:Java的异常处理机制是什么
java·开发语言·后端·面试
無限進步D4 小时前
Java 面向对象高级 接口
java·开发语言
两年半的个人练习生^_^5 小时前
Java日志框架和使用、日志记录规范
java·开发语言·开发规范
techdashen5 小时前
Pingora 的开源——Cloudflare 基于 Rust 搭建的用于替换Nginx的网络框架
nginx·rust·开源
杨凯凡6 小时前
【032】排查入门:jstack、heap dump、Arthas 初识
java·开发语言·后端
其实防守也摸鱼6 小时前
无线网络安全--实验 规避WLAN验证之发现隐藏的SSID
java·开发语言·网络·安全·web安全·智能路由器·无线网络安全
l1t6 小时前
astral-sh发布的musl和gnu版本standalone python 性能比较
开发语言·python