rust打印变量类型

本文介绍了如何在Rust中使用不稳定的方法std::any::type_name来获取并打印变量的类型,通过HashSet和Vec的示例展示了其用法。注意,这种方法可能在后续版本中改变。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

可以试试std::any::type_name。注意,这个是unstable的。

use std::collections::HashSet;

fn print_type_of<T>(_: &T) {
    println!("{}", std::any::type_name::<T>())
}

fn main() {
    let mut s = HashSet::new();
    let ve = vec![1, 2, 1, 3, 2, 4];
    print_type_of(&s);
    for v in &ve {
        println!("{}", s.insert(v));
    }
}
std::collections::hash::set::HashSet<&i32>
true
true
false
true
false
true

参考文献:
如何在Rust中打印一个变量的类型?
https://stackoverflow.com/questions/21747136/how-do-i-print-the-type-of-a-variable-in-rust/43508373#43508373
https://doc.rust-lang.org/stable/std/any/fn.type_name.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值