Why there is no intrinsic `type_name_val`?

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.

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

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>()
}
1 Like

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

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.