首页 > 其他 > 详细

如何在Rust中打印变量的类型及类型转换实践

时间:2021-08-19 22:14:26      阅读:31      评论:0      收藏:0      [点我收藏+]
#![feature(core_intrinsics)]
fn print_type_of<T>(_: T) {
    println!("{}", std::intrinsics::type_name::<T>() );
}

fn main() {
    print_type_of(3);       // prints "i32"
    print_type_of(32.90);   // prints "f64"
    print_type_of(vec![102, 111, 111]);                // prints "alloc::vec::Vec<i32>"
    print_type_of(b"foo12".to_vec());            // prints "alloc::vec::Vec<u8>" 
    print_type_of(b"foo12".to_owned());            // prints "[u8; 5]"  
    print_type_of( "bar".as_bytes().to_vec());   // prints "alloc::vec::Vec<u8>"   
    print_type_of( "bar".as_bytes().to_owned());   // prints "alloc::vec::Vec<u8>"   
    println!("===================================================");
    print_type_of("foo");            // prints "&str"   
    let s = "bar";       
    print_type_of(&s);               // prints "&&str"   
    print_type_of(*&s);               // prints "&str"  
    print_type_of(&&s);               // prints "&&&str"    
    print_type_of([0x08, 0x09, 0x0a, 0x0b, ]);           // prints "[i32; 4]"   
    print_type_of([0x08, 0x09, 0x0a, 0x0b, 0x0b,]);      // prints "[i32; 5]"   
    print_type_of("foo".as_bytes());                     // prints "&[u8]"   
    print_type_of(b"foo15");                             // prints "&[u8; 5]"    
    print_type_of("foo".to_string());    // prints "alloc::string::String"  
    print_type_of("foo".to_owned());     // prints "alloc::string::String"   
    print_type_of(String::from("foo"));  // prints "alloc::string::String"    
    print_type_of(String::from_utf8(vec![102, 111, 111]).unwrap());          //prints "alloc::string::String"  
    println!("{}",String::from_utf8(vec![102, 111, 111]).unwrap());          //prints "foo"  
    print_type_of(std::str::from_utf8(&[0x66, 0x6F, 0x6F,]).unwrap());       //prints "&str"  
    println!("{}",std::str::from_utf8(&[0x66, 0x6F, 0x6F,]).unwrap());       //prints "foo"  
    println!("{}",std::str::from_utf8(&[102, 111, 111,]).unwrap());          //prints "foo"  
    println!("{}",std::str::from_utf8( "foo".as_bytes()).unwrap());          //prints "foo" 
    println!("{}",std::str::from_utf8(&vec![102, 111, 111]).unwrap());       //prints "foo" 
    print_type_of(vec![102, 111, 111].as_slice());       //prints "&[i32]" 
    println!("{:?}",vec![102, 111, 111].as_slice());     //prints "[102, 111, 111]"

    
}

需要切换rustup到nightly版本才能运行cargo run 

如何切换 可参考上一篇文章

 

参考:https://www.cnblogs.com/chen8840/p/12698527.html

https://zhuanlan.zhihu.com/p/372082802

https://blog.csdn.net/wowotuo/article/details/83927644

https://cloud.tencent.com/developer/ask/66463

 

如何在Rust中打印变量的类型及类型转换实践

原文:https://www.cnblogs.com/pu369/p/15163424.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!