简体   繁体   中英

How to get the type of a variable so I can call a turbofish function?

Sometimes I have a variable, and I want to call a 'turbofish' function with the variable's type. For example:

fn main() {
    let arr = [0u8; 4];
    println!("size_of arr: {}", std::mem::size_of::< TYPE_OF(arr) >());
}

Of course, TYPE_OF() doesn't exist. So I end up having to hard-code the type manually:

println!("size_of arr: {}", std::mem::size_of::< [u8;4] >());

It sure would be nice if I could get the type of a variable (at compile-time, not runtime) so I didn't need to hard-code the type myself.

For your particular example, there is already a function in std to get the size of a type, based on its value; std::mem::size_of_val :

println!("size_of arr: {}", std::mem::size_of_val(&arr));

In general, if you want to bind a type variable to a type, you probably need to do it in the body of a function. For example, if size_of_val did not exist, you could do:

fn main() {
    fn size_of_val<T>(_: &T) -> usize {
        std::mem::size_of::<T>()
    }
    let arr = [0u8; 4];
    println!("size_of arr: {}", size_of_val(&arr));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM