Flashcard Rust: What type is this variable again?!
This is going to be a very short post on a tiny function that can help us in figuring out what is the type of a variable.
This is helpful to me personally when learning rust and after some hours of coding, I want to know what is the type of a variable quickly, which is not easy always.I need to thank @timClicks for showing this in one of his streams on youtube. If you are learning Rust and is looking for a book, let me please recommend Rust in Action by Tim, it is an excellent in-depth introduction to Rust.
What is it ?
use std::any::type_name;
// what is the type of the passed argument
fn what_type<T>(_: &T) {
println!("type is: {}", type_name::<T>());
}
type_name
function from the std
crate returns the name of a type as a string slice.
Before knowing about this function available from the std crate(reminder to self, to read the standard library docs!), i tended to use the ide introspection features to confirm what the type of a variable was at times or use a ()
as type and the compiler complains to me that the type is something else, which is what i wanted to known in the first place, but know I have a shiny new function that I can use, lets see how it works.
How is it used ?
Let’s take a simple example,
fn main() {
let number = 3232;
let name = "Rahul".to_string();
let list_of_nums = vec![1, 2, ];
&number);
what_type(&name);
what_type(&list_of_nums);
what_type(}
That is it, and it will print the type of the variable passed into the what_type function as below:
type is: i32
type is: alloc::string::String
type is: alloc::vec::Vec<i32>
References
End
Like I said a short post about a really useful(hopefully) function in Rust.