Get the type of a var

Hi there. I'm a Rust noob so, plz, excuse me for my questions.

The first is: how can print the type of a variable? That is, for example in C# i can write:

int x = 5;
Console.WriteLine(x.GetType());

Is it possibile to get the same result in Rust?

Thx.

You can use std::intrinsics::type_name() but it is not stable so you must use a nightly build and add #![feature(core_intrinsics)] to your crate root.
It takes a type parameter <T> instead of reading the type of the argument. I think this is because Rust doesn't have type information at runtime. (unlike C# and the CLR)

Here's a simple example:

#![feature(core_intrinsics)]

use std::intrinsics::type_name;

fn test_type<T>(_: T) {
    println!("{:?}", unsafe { type_name::<T>() });
}

fn main() {
    test_type(5);
}

That will output "i32"

Quite complicated....:slight_smile: I'm using 1.40 stable.... ok, if this is the only way i can wait untile intrinsics will be stable,
thx.

Looking at the documentation, they say this is 'unlikely to ever be stabilized'.
And yes, I feel that this isn't quite the Rusty way of doing things. May I ask what you are trying to achieve overall? because there is probably an alternative way of doing things.

Hopefully that helps. :smile:

ps: if you're looking to do dynamic typing then perhaps std::any will help?

That is the strangest function signature I've ever seen. You specialize it to something so that you avoid an input parameter? Maybe there's a good reason for it but that looks bizarre.

Nothing really important :wink: i'm trying to learn Rust and the path I have chosen is to set up a parallelism between what I know best (C#) and rust

The reason is that Rust doesn't have type information at runtime except with trait objects. And you may not always have an instance to pass in. size_of::<T>() also works the same way.

As far as debugging goes, a little trick:

let x = ......; // don't know the type of x

let y: () = x;  // will throw a type error with the name of x's type
3 Likes