Function std::any::type_name

Hello, is it possible to write an expression in one line to print the type of a variable using the function from the subject?

Well, if you really want a one-liner - here it is:

fn main() {
    let var = Some(("s", 1, 1.0));
    let name = {fn tmp<T>(_: T) -> &'static str {std::any::type_name::<T>()}; tmp}(var);
    println!("{}", name);
}

Ugly, but it works - playground.

I'd advise, anyway, not to insist on the one-line solution and to extract the function from the block.

2 Likes

I thought it was impossible to write in the form of a simple function call. Thank you, I just started to study Rust, and thought I missed something.

In any case, your code looks very cool. Thanks again!

Note this doesn't universally work. It happens to work in your example because the type of var is Copy. The following doesn't compile:

fn main() {
    let var = Some((String::from("s"), 1, 1.0));
    let name = {fn tmp<T>(_: T) -> &'static str {std::any::type_name::<T>()}; tmp}(var);
    println!("{}: {:?}", name, var);
}

(playground)
Because var is moved by the function call.

The following, however, does work in more cases:

fn main() {
    let var = Some((String::from("s"), 1, 1.0));
    let name = {fn tmp<T>(_: &T) -> &'static str {std::any::type_name::<T>()}; tmp}(&var);
    println!("{}: {:?}", name, var);
}

(playground)

2 Likes

Thanks, missed the possibility that the function argument and the type parameter might be different.