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

相关推荐
炘爚几秒前
C语言(文件操作)
c语言·开发语言
阿蒙Amon4 分钟前
C#常用类库-详解SerialPort
开发语言·c#
凸头24 分钟前
CompletableFuture 与 Future 对比与实战示例
java·开发语言
wuqingshun31415927 分钟前
线程安全需要保证几个基本特征
java·开发语言·jvm
Moksha26232 分钟前
5G、VoNR基本概念
开发语言·5g·php
jzlhll1231 小时前
kotlin Flow first() last()总结
开发语言·前端·kotlin
W.D.小糊涂1 小时前
gpu服务器安装windows+ubuntu24.04双系统
c语言·开发语言·数据库
用头发抵命1 小时前
Vue 3 中优雅地集成 Video.js 播放器:从组件封装到功能定制
开发语言·javascript·ecmascript
似水明俊德1 小时前
02-C#.Net-反射-学习笔记
开发语言·笔记·学习·c#·.net
于先生吖2 小时前
Java框架开发短剧漫剧系统:后台管理与接口开发
java·开发语言