I need to find out type of a variable, In python I could do it via type(), How can I do it in rust?
What do you need this for? Rust is statically typed; types are a compile-time rather than a runtime construct, so there's no direct equivalent to Python's type
function.
If you are only interested in a type because you are trying to understand some code or a compile error better, you can try to generate a type error artificially, so that the error message includes a type mismatch:
struct NotAnyOtherType;
let _: NotAnyOtherType = <the variable you want to inspect>;
If you just need to know to aid in development, you can print the type name like this:
fn dbg_type_of<T>(_:&T) {
dbg!(std::any::type_name::<T>());
}
fn main() {
let x = 5;
dbg_type_of(&x);
}
The exact output of this is subject to change, though, so you shouldn't use it to make decisions at runtime. If you want to do that, there are other ways, but we'd need to know more about what you're trying to do in order to give the proper advice.
Finding types of things in general is very likely not the right approach in Rust.
It depends on what you need this for.
-
If some object (variable) can be one of a few things, then make it an
enum
and test with amatch
-
If it can be any type, then don't check the type, but define a
trait
that does what you want regardless of the type. e.g. instead of something likeif is integer { print_int(a); } else if is a string { print_string(a);}
we haveDisplay
trait that prints any printable type. -
There's
Any
trait anddowncast
as the last resort for working with unknown types, but it's not an equivalent of what you can do in Python.
Generally, if you think you need to check type of something, take a few steps back, and try to redesign it so that you never need to check a type.
There's a couple of different ways to answer the question, depending on what you need to do.
I think it's great to install and use rust-analyzer with your editor, if you can. The it can display types for variables in the code while you're working on or reading code.
Check out the documentation for the std::any module. In a generic context, if you just need type equivalence, you can use the Any trait in combination with the TypeId struct. Example:
use std::any::{Any, TypeId};
fn print_it<T: Any>(it: T) {
if it.type_id() == TypeId::of::<i32>() {
println!("we have an i32");
} else {
panic!("we do not have an i32");
}
}
fn main() {
print_it(1i32); // prints
print_it(1i64); // panics
}
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.