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

相关推荐
He19550118 分钟前
wordpress搭建块
开发语言·wordpress·古腾堡·wordpress块
老天文学家了43 分钟前
蓝桥杯备战Python
开发语言·python
赫瑞1 小时前
数据结构中的排列组合 —— Java实现
java·开发语言·数据结构
初夏睡觉1 小时前
c++1.3(变量与常量,简单数学运算详解),草稿公放
开发语言·c++
升职佳兴1 小时前
C盘爆满自救:3步无损迁移应用数据到E盘(含回滚)
c语言·开发语言
ID_180079054731 小时前
除了 Python,还有哪些语言可以解析 JSON 数据?
开发语言·python·json
周末也要写八哥2 小时前
多进程和多线程的特点和区别
java·开发语言·jvm
土豆12502 小时前
Tauri 入门与实践:用 Rust 构建你的下一个桌面应用
前端·rust
土豆12502 小时前
Rust 错误处理实战:anyhow + thiserror 的黄金搭档
rust
宁瑶琴3 小时前
COBOL语言的云计算
开发语言·后端·golang