Skip to content

Commit 0ae4a19

Browse files
authored
Rollup merge of rust-lang#65961 - lcnr:typename_of, r=Dylan-DPC
add fn type_name_of_val This function is often useful during testing and mirrors `align_of_val` and `size_of_val`. # Example Showing the default type of integers. ```rust let x = 7; println!("per default, integers have the type: {}", std::any::type_name_of_val(&x)); ``` To my knowledge this can currently not be done without defining a function similar to `type_name_of_val`.
2 parents a449535 + 985e663 commit 0ae4a19

File tree

1 file changed

+40
-1
lines changed

1 file changed

+40
-1
lines changed

src/libcore/any.rs

+40-1
Original file line numberDiff line numberDiff line change
@@ -452,7 +452,7 @@ impl TypeId {
452452
/// The current implementation uses the same infrastructure as compiler
453453
/// diagnostics and debuginfo, but this is not guaranteed.
454454
///
455-
/// # Example
455+
/// # Examples
456456
///
457457
/// ```rust
458458
/// assert_eq!(
@@ -465,3 +465,42 @@ impl TypeId {
465465
pub const fn type_name<T: ?Sized>() -> &'static str {
466466
intrinsics::type_name::<T>()
467467
}
468+
469+
/// Returns the name of the type of the pointed-to value as a string slice.
470+
/// This is the same as `type_name::<T>()`, but can be used where the type of a
471+
/// variable is not easily available.
472+
///
473+
/// # Note
474+
///
475+
/// This is intended for diagnostic use. The exact contents and format of the
476+
/// string are not specified, other than being a best-effort description of the
477+
/// type. For example, `type_name_of::<Option<String>>(None)` could return the
478+
/// `"Option<String>"` or `"std::option::Option<std::string::String>"`, but not
479+
/// `"foobar"`. In addition, the output may change between versions of the
480+
/// compiler.
481+
///
482+
/// The type name should not be considered a unique identifier of a type;
483+
/// multiple types may share the same type name.
484+
///
485+
/// The current implementation uses the same infrastructure as compiler
486+
/// diagnostics and debuginfo, but this is not guaranteed.
487+
///
488+
/// # Examples
489+
///
490+
/// Prints the default integer and float types.
491+
///
492+
/// ```rust
493+
/// #![feature(type_name_of_val)]
494+
/// use std::any::type_name_of_val;
495+
///
496+
/// let x = 1;
497+
/// println!("{}", type_name_of_val(&x));
498+
/// let y = 1.0;
499+
/// println!("{}", type_name_of_val(&y));
500+
/// ```
501+
#[unstable(feature = "type_name_of_val", issue = "66359")]
502+
#[rustc_const_unstable(feature = "const_type_name")]
503+
pub const fn type_name_of_val<T: ?Sized>(val: &T) -> &'static str {
504+
let _ = val;
505+
type_name::<T>()
506+
}

0 commit comments

Comments
 (0)