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

相关推荐
天下无敌笨笨熊6 小时前
C#Modbus串口开发心得
开发语言·c#
电商API_180079052476 小时前
电商商品价格监控工具淘宝京东商品价格抓取API项目实操分享
java·大数据·开发语言·前端·数据挖掘
zzzll11116 小时前
深度剖析:HashMap 并发死循环与 ConcurrentHashMap 两代演进全解
java·开发语言
如意猴6 小时前
【C++】001--C++入门(1)
开发语言·c++
2601_962294616 小时前
AI 基础设施的“去 Python 化“:Rust 与 C# 的两条替代路径
ai·rust·c·基础设施·去python化
传奇开心果编程6 小时前
【Rust入门知识点学与练】第10课:Option 和 Result(错误处理入门)
开发语言·学习·rust
leonkay6 小时前
C# 锁机制——【2】深入原理
开发语言·后端·spring·c#·个人开发
坐吃山猪7 小时前
【多线程】CompletableFuture使用
java·开发语言·多线程
CHPCWWHSU7 小时前
DeepSeek-Harness-Qt将浏览器端Agent装入桌面应用
开发语言·qt
前端 贾公子7 小时前
第10章:RAG(2)
开发语言·python