首页 > 其他分享 >Rust中获取类型名的方法typeof

Rust中获取类型名的方法typeof

时间:2023-01-01 12:32:51浏览次数:55  
标签:string i32 获取 let typeof println type Rust vec

Rust中获取类型名的方法

  • 实现方式
use std::collections::VecDeque;

fn type_of<T>(_: T) -> &'static str {
    std::any::type_name::<T>()
    // std::intrinsics::type_name::<T>()
}

fn main() {
    let type_i32: i32 = 0;
    println!("type_i32: {}", type_of(type_i32));

    let type_float64: f64 = 1.0;
    println!("type_float64: {}", type_of(type_float64));

    let type_char: char = 'a';
    println!("type_char: {}", type_of(type_char));

    let type_static_string = "hello world";
    println!("type_static_string: {}", type_of(type_static_string));

    let type_string: String = String::new();
    println!("type_string: {}", type_of(type_string));

    let type_arr = [1, 2, 3];
    println!("type_arr: {}", type_of(type_arr));

    let type_vec = Vec::<i32>::new();
    println!("type_vec: {}", type_of(type_vec));

    let type_vec_deque = VecDeque::<i32>::new();
    println!("type_vec_deque: {}", type_of(type_vec_deque));
}
  • 结果输出
type_i32: i32
type_float64: f64
type_char: char
type_static_string: &str
type_string: alloc::string::String
type_arr: [i32; 3]
type_vec: alloc::vec::Vec<i32>
type_vec_deque: alloc::collections::vec_deque::VecDeque<i32>

官方说明

【std::any::type_name】https://doc.rust-lang.org/std/any/fn.type_name.html

标签:string,i32,获取,let,typeof,println,type,Rust,vec
From: https://blog.51cto.com/xdataplus/5982929

相关文章