How to print the type of a variable?

Is there a way to print the type of a variable?

Having this code:

fn main() {
    let a = vec![2, 3];
    println!("{}", a);
}

I get a compile error:

`Vec<{integer}>` doesn't implement `std::fmt::Display`

So not surprisingly the compiler know what type is the variable a

Is there a macro or a formatting option I could use in println! that would print Vec<{integer}> when the a variable is supplied?

Vec<{integer}> is not quote the type here, actual type is Vec<i32>

2 Likes

Thanks, but I don't seem to be able to use this. Where do I put the a variable?

Something like this. You can call it as print_type(&a).

fn print_type<T>(_: &T) { 
    println!("{:?}", std::any::type_name::<T>());
}
1 Like

That worked quite well. Thanks.

It seems such a neat tool for understand code, why is this function, the way you wrote it, not part of the standard library?

It is, it's just not stabilized yet, due to some corner cases.

1 Like

Are you using rust-analyzer? It integrates into your editor and prints types of all the variables inside the editor itself.

@Cerber-Ursi thanks for the link

@manpacket When I use VS Code then I do have rust-analyzer, but I write a lot in vim and I have not set up the integration yet.

You can add it to vim as well with this: GitHub - simrat39/rust-tools.nvim: Tools for better development in rust using neovim's builtin lsp

1 Like

If you just need to know in development, a trick is to cause a type error:

let a: () = vec![2,3];

will print something like expected (), but found Vec<i32>.

5 Likes

A pedantic tangent:

You will never get a program to print Vec<{integer}> as a type name. This is because {integer} is a pseudo-type that only appears when a program is being compiled: it means “some integer type we haven't yet decided on” (that came from an integer literal). When the compiler finishes, it will always have either replaced {integer} with a specific integer type (i32 if nothing else constrains it), or have reported a fatal error. Any successfully compiled program contains no {integer}s.

2 Likes

Thanks for the explanation. That now also explains why it said "integer", something that was not clear to me in this and in other cases.

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.