I have the following:
let mut my_number = 32.90;
How do I print the type of my_number
?
Using type
and type_of
did not work. Is there another way I can print the number's type?
I have the following:
let mut my_number = 32.90;
How do I print the type of my_number
?
Using type
and type_of
did not work. Is there another way I can print the number's type?
You can use the
std::any::type_name
function. This doesn't need a nightly compiler or an external crate, and the results are quite correct:Be warned: as said in the documentation, this information must be used for a debug purpose only:
If you want your type representation to stay the same between compiler versions, you should use a trait, like in the phicr's answer.
If you merely wish to find out the type of a variable and are willing to do it at compile time, you can cause an error and get the compiler to pick it up.
For example, set the variable to a type which doesn't work:
Or call an invalid method:
Or access an invalid field:
These reveal the type, which in this case is actually not fully resolved. It’s called “floating-point variable” in the first example, and “
{float}
” in all three examples; this is a partially resolved type which could end upf32
orf64
, depending on how you use it. “{float}
” is not a legal type name, it’s a placeholder meaning “I’m not completely sure what this is”, but it is a floating-point number. In the case of floating-point variables, if you don't constrain it, it will default tof64
¹. (An unqualified integer literal will default toi32
.)See also:
¹ There may still be ways of baffling the compiler so that it can’t decide between
f32
andf64
; I’m not sure. It used to be as simple as32.90.eq(&32.90)
, but that treats both asf64
now and chugs along happily, so I don’t know.I put together a little crate to do this based off vbo's answer. It gives you a macro to return or print out the type.
Put this in your Cargo.toml file:
Then you can use it like so:
There is an unstable function
std::intrinsics::type_name
that can get you the name of a type, though you have to use a nightly build of Rust (this is unlikely to ever work in stable Rust). Here’s an example:UPD The following does not work anymore. Check Shubham's answer for correction.
Check out
std::intrinsics::get_tydesc<T>()
. It is in "experimental" state right now, but it's OK if you are just hacking around the type system.Check out the following example:
This is what is used internally to implement the famous
{:?}
formatter.There's a @ChrisMorgan answer to get approximate type ("float") in stable rust and there's a @ShubhamJain answer to get precise type ("f64") through unstable function in nightly rust.
Now here's a way one can get precise type (ie decide between f32 and f64) in stable rust:
results in
Update
The turbofish variation
is slightly shorter but somewhat less readable.