Why there is no intrinsic `type_name_val`?


#1

There is an intrinsic type_name, but no corresponding type_name_val.

For comparison, there are both size_of and size_of_val.

Is there any reason not to have it? Or is there any relationship between this function and unimplemented typeof keyword?

I can name several scenarios on top of my head that type_name_val is much more useful than type_name.


#2

Type names, unlike sizes, are only known at compile time.


#3

You cannot define size_of_val in terms of size_of.

fn main() {
    let f: &str = "size_of_val";

    // There is no such thing as size of `str` because the size is
    // not necessarily known at compile time.
    println!("{}", std::mem::size_of::<str>());

    // This looks at the size of the specific `str` value at runtime.
    // In this case 11.
    println!("{}", std::mem::size_of_val::<str>(f));
}

But you can define type_name_val.

#![feature(core_intrinsics)]

fn main() {
    // Prints `[u8; 21]`
    println!("{}", unsafe { type_name_val(b"a byte string literal") });
}

unsafe fn type_name_val<T: ?Sized>(_val: &T) -> &'static str {
    std::intrinsics::type_name::<T>()
}

#4

Oh~ Thanks very much! That is what I want.