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

相关推荐
萌动的小火苗5 分钟前
1、python基础面试题
java·开发语言·python
运维行者_15 分钟前
网络监控与ITSM集成:从告警到工单,实现运维自动化闭环
开发语言·网络·分布式·后端·架构·flask·php
小叮当爱咖啡39 分钟前
Day3.参数+Prompt三板斧
开发语言·python·prompt
菜冻鱼1 小时前
Python-pandas-索引与筛选
开发语言·笔记·python·numpy·pandas·学习方法
鹿角片ljp1 小时前
Java面试复盘(二):String不可变、字符串常量池与字符串拼接
开发语言·python
小秋求学记.2 小时前
PHP安全漏洞实战:从环境配置到RCE攻击
开发语言·php
看浪的路人2 小时前
第3讲:代码补全引擎
开发语言·windows·python
小小龙学IT3 小时前
Day 26-27 项目实战:从零构建一个高并发聊天室(epoll + 线程池)
linux·服务器·c语言·开发语言·网络
梦醒沉醉3 小时前
15、Rust程序设计语言——无畏并发
rust
我就是妖怪3 小时前
【无标题】
开发语言