1

How to print out type of any variable in Ruts?

Thanks in advance!

use std::any::Any;
use std::any::type_name;


fn main() {
    let x = 5;
    let x = x + 1;
    let x = x * 2;
    println!("{}", x);
    let spaces = "       ";
    let spaces = spaces.len();
    println!("{}", String::from_utf16(&spaces));
}
NIk
  • 123
  • 5
  • 2
    If you're using nightly, [std::any::type_name_of_val](https://doc.rust-lang.org/std/any/fn.type_name_of_val.html), otherwise you cannot. – Kaihaku Sep 19 '21 at 12:01
  • 3
    @Kaihaku Nightly is not necessary at all. `std::any::type_name_of_val` is just a simple generic wrapper around [`type_name`](https://doc.rust-lang.org/std/any/fn.type_name.html) and can be easily recreated. – Aplet123 Sep 19 '21 at 12:02
  • 2
    @Aplet123 my bad, you're right, you have everything you need to implement it yourself: `fn value_type_name(_: &T) -> &'static str { std::any::type_name::() }` [Playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=4f8720732d8b7843df83cf30615c568a) – Kaihaku Sep 19 '21 at 12:11
  • Thanks. I am beginner suggest a code for printing our space (variable in my example). Cheers – NIk Sep 19 '21 at 18:56

0 Answers0