]> git.lizzy.rs Git - rust.git/blob - library/core/src/any.rs
add tracking issue for `downcast_unchecked`
[rust.git] / library / core / src / any.rs
1 //! This module implements the `Any` trait, which enables dynamic typing
2 //! of any `'static` type through runtime reflection.
3 //!
4 //! `Any` itself can be used to get a `TypeId`, and has more features when used
5 //! as a trait object. As `&dyn Any` (a borrowed trait object), it has the `is`
6 //! and `downcast_ref` methods, to test if the contained value is of a given type,
7 //! and to get a reference to the inner value as a type. As `&mut dyn Any`, there
8 //! is also the `downcast_mut` method, for getting a mutable reference to the
9 //! inner value. `Box<dyn Any>` adds the `downcast` method, which attempts to
10 //! convert to a `Box<T>`. See the [`Box`] documentation for the full details.
11 //!
12 //! Note that `&dyn Any` is limited to testing whether a value is of a specified
13 //! concrete type, and cannot be used to test whether a type implements a trait.
14 //!
15 //! [`Box`]: ../../std/boxed/struct.Box.html
16 //!
17 //! # Smart pointers and `dyn Any`
18 //!
19 //! One piece of behavior to keep in mind when using `Any` as a trait object,
20 //! especially with types like `Box<dyn Any>` or `Arc<dyn Any>`, is that simply
21 //! calling `.type_id()` on the value will produce the `TypeId` of the
22 //! *container*, not the underlying trait object. This can be avoided by
23 //! converting the smart pointer into a `&dyn Any` instead, which will return
24 //! the object's `TypeId`. For example:
25 //!
26 //! ```
27 //! use std::any::{Any, TypeId};
28 //!
29 //! let boxed: Box<dyn Any> = Box::new(3_i32);
30 //!
31 //! // You're more likely to want this:
32 //! let actual_id = (&*boxed).type_id();
33 //! // ... than this:
34 //! let boxed_id = boxed.type_id();
35 //!
36 //! assert_eq!(actual_id, TypeId::of::<i32>());
37 //! assert_eq!(boxed_id, TypeId::of::<Box<dyn Any>>());
38 //! ```
39 //!
40 //! # Examples
41 //!
42 //! Consider a situation where we want to log out a value passed to a function.
43 //! We know the value we're working on implements Debug, but we don't know its
44 //! concrete type. We want to give special treatment to certain types: in this
45 //! case printing out the length of String values prior to their value.
46 //! We don't know the concrete type of our value at compile time, so we need to
47 //! use runtime reflection instead.
48 //!
49 //! ```rust
50 //! use std::fmt::Debug;
51 //! use std::any::Any;
52 //!
53 //! // Logger function for any type that implements Debug.
54 //! fn log<T: Any + Debug>(value: &T) {
55 //!     let value_any = value as &dyn Any;
56 //!
57 //!     // Try to convert our value to a `String`. If successful, we want to
58 //!     // output the String`'s length as well as its value. If not, it's a
59 //!     // different type: just print it out unadorned.
60 //!     match value_any.downcast_ref::<String>() {
61 //!         Some(as_string) => {
62 //!             println!("String ({}): {}", as_string.len(), as_string);
63 //!         }
64 //!         None => {
65 //!             println!("{:?}", value);
66 //!         }
67 //!     }
68 //! }
69 //!
70 //! // This function wants to log its parameter out prior to doing work with it.
71 //! fn do_work<T: Any + Debug>(value: &T) {
72 //!     log(value);
73 //!     // ...do some other work
74 //! }
75 //!
76 //! fn main() {
77 //!     let my_string = "Hello World".to_string();
78 //!     do_work(&my_string);
79 //!
80 //!     let my_i8: i8 = 100;
81 //!     do_work(&my_i8);
82 //! }
83 //! ```
84
85 #![stable(feature = "rust1", since = "1.0.0")]
86
87 use crate::fmt;
88 use crate::intrinsics;
89
90 ///////////////////////////////////////////////////////////////////////////////
91 // Any trait
92 ///////////////////////////////////////////////////////////////////////////////
93
94 /// A trait to emulate dynamic typing.
95 ///
96 /// Most types implement `Any`. However, any type which contains a non-`'static` reference does not.
97 /// See the [module-level documentation][mod] for more details.
98 ///
99 /// [mod]: crate::any
100 // This trait is not unsafe, though we rely on the specifics of it's sole impl's
101 // `type_id` function in unsafe code (e.g., `downcast`). Normally, that would be
102 // a problem, but because the only impl of `Any` is a blanket implementation, no
103 // other code can implement `Any`.
104 //
105 // We could plausibly make this trait unsafe -- it would not cause breakage,
106 // since we control all the implementations -- but we choose not to as that's
107 // both not really necessary and may confuse users about the distinction of
108 // unsafe traits and unsafe methods (i.e., `type_id` would still be safe to call,
109 // but we would likely want to indicate as such in documentation).
110 #[stable(feature = "rust1", since = "1.0.0")]
111 #[cfg_attr(not(test), rustc_diagnostic_item = "Any")]
112 pub trait Any: 'static {
113     /// Gets the `TypeId` of `self`.
114     ///
115     /// # Examples
116     ///
117     /// ```
118     /// use std::any::{Any, TypeId};
119     ///
120     /// fn is_string(s: &dyn Any) -> bool {
121     ///     TypeId::of::<String>() == s.type_id()
122     /// }
123     ///
124     /// assert_eq!(is_string(&0), false);
125     /// assert_eq!(is_string(&"cookie monster".to_string()), true);
126     /// ```
127     #[stable(feature = "get_type_id", since = "1.34.0")]
128     fn type_id(&self) -> TypeId;
129 }
130
131 #[stable(feature = "rust1", since = "1.0.0")]
132 impl<T: 'static + ?Sized> Any for T {
133     fn type_id(&self) -> TypeId {
134         TypeId::of::<T>()
135     }
136 }
137
138 ///////////////////////////////////////////////////////////////////////////////
139 // Extension methods for Any trait objects.
140 ///////////////////////////////////////////////////////////////////////////////
141
142 #[stable(feature = "rust1", since = "1.0.0")]
143 impl fmt::Debug for dyn Any {
144     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
145         f.debug_struct("Any").finish_non_exhaustive()
146     }
147 }
148
149 // Ensure that the result of e.g., joining a thread can be printed and
150 // hence used with `unwrap`. May eventually no longer be needed if
151 // dispatch works with upcasting.
152 #[stable(feature = "rust1", since = "1.0.0")]
153 impl fmt::Debug for dyn Any + Send {
154     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
155         f.debug_struct("Any").finish_non_exhaustive()
156     }
157 }
158
159 #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
160 impl fmt::Debug for dyn Any + Send + Sync {
161     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
162         f.debug_struct("Any").finish_non_exhaustive()
163     }
164 }
165
166 impl dyn Any {
167     /// Returns `true` if the inner type is the same as `T`.
168     ///
169     /// # Examples
170     ///
171     /// ```
172     /// use std::any::Any;
173     ///
174     /// fn is_string(s: &dyn Any) {
175     ///     if s.is::<String>() {
176     ///         println!("It's a string!");
177     ///     } else {
178     ///         println!("Not a string...");
179     ///     }
180     /// }
181     ///
182     /// is_string(&0);
183     /// is_string(&"cookie monster".to_string());
184     /// ```
185     #[stable(feature = "rust1", since = "1.0.0")]
186     #[inline]
187     pub fn is<T: Any>(&self) -> bool {
188         // Get `TypeId` of the type this function is instantiated with.
189         let t = TypeId::of::<T>();
190
191         // Get `TypeId` of the type in the trait object (`self`).
192         let concrete = self.type_id();
193
194         // Compare both `TypeId`s on equality.
195         t == concrete
196     }
197
198     /// Returns some reference to the inner value if it is of type `T`, or
199     /// `None` if it isn't.
200     ///
201     /// # Examples
202     ///
203     /// ```
204     /// use std::any::Any;
205     ///
206     /// fn print_if_string(s: &dyn Any) {
207     ///     if let Some(string) = s.downcast_ref::<String>() {
208     ///         println!("It's a string({}): '{}'", string.len(), string);
209     ///     } else {
210     ///         println!("Not a string...");
211     ///     }
212     /// }
213     ///
214     /// print_if_string(&0);
215     /// print_if_string(&"cookie monster".to_string());
216     /// ```
217     #[stable(feature = "rust1", since = "1.0.0")]
218     #[inline]
219     pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
220         if self.is::<T>() {
221             // SAFETY: just checked whether we are pointing to the correct type, and we can rely on
222             // that check for memory safety because we have implemented Any for all types; no other
223             // impls can exist as they would conflict with our impl.
224             unsafe { Some(self.downcast_ref_unchecked()) }
225         } else {
226             None
227         }
228     }
229
230     /// Returns some mutable reference to the inner value if it is of type `T`, or
231     /// `None` if it isn't.
232     ///
233     /// # Examples
234     ///
235     /// ```
236     /// use std::any::Any;
237     ///
238     /// fn modify_if_u32(s: &mut dyn Any) {
239     ///     if let Some(num) = s.downcast_mut::<u32>() {
240     ///         *num = 42;
241     ///     }
242     /// }
243     ///
244     /// let mut x = 10u32;
245     /// let mut s = "starlord".to_string();
246     ///
247     /// modify_if_u32(&mut x);
248     /// modify_if_u32(&mut s);
249     ///
250     /// assert_eq!(x, 42);
251     /// assert_eq!(&s, "starlord");
252     /// ```
253     #[stable(feature = "rust1", since = "1.0.0")]
254     #[inline]
255     pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
256         if self.is::<T>() {
257             // SAFETY: just checked whether we are pointing to the correct type, and we can rely on
258             // that check for memory safety because we have implemented Any for all types; no other
259             // impls can exist as they would conflict with our impl.
260             unsafe { Some(self.downcast_mut_unchecked()) }
261         } else {
262             None
263         }
264     }
265
266     /// Returns a reference to the inner value as type `dyn T`.
267     ///
268     /// For a safe alternative see [`downcast_ref`].
269     ///
270     /// # Examples
271     ///
272     /// ```
273     /// #![feature(downcast_unchecked)]
274     ///
275     /// use std::any::Any;
276     ///
277     /// let x: Box<dyn Any> = Box::new(1_usize);
278     ///
279     /// unsafe {
280     ///     assert_eq!(*x.downcast_ref_unchecked::<usize>(), 1);
281     /// }
282     /// ```
283     ///
284     /// # Safety
285     ///
286     /// The contained value must be of type `T`. Calling this method
287     /// with the incorrect type is *undefined behavior*.
288     #[unstable(feature = "downcast_unchecked", issue = "90850")]
289     #[inline]
290     pub unsafe fn downcast_ref_unchecked<T: Any>(&self) -> &T {
291         debug_assert!(self.is::<T>());
292         // SAFETY: caller guarantees that T is the correct type
293         unsafe { &*(self as *const dyn Any as *const T) }
294     }
295
296     /// Returns a mutable reference to the inner value as type `dyn T`.
297     ///
298     /// For a safe alternative see [`downcast_mut`].
299     ///
300     /// # Examples
301     ///
302     /// ```
303     /// #![feature(downcast_unchecked)]
304     ///
305     /// use std::any::Any;
306     ///
307     /// let mut x: Box<dyn Any> = Box::new(1_usize);
308     ///
309     /// unsafe {
310     ///     *x.downcast_mut_unchecked::<usize>() += 1;
311     /// }
312     ///
313     /// assert_eq!(*x.downcast_ref::<usize>().unwrap(), 2);
314     /// ```
315     ///
316     /// # Safety
317     ///
318     /// The contained value must be of type `T`. Calling this method
319     /// with the incorrect type is *undefined behavior*.
320     #[unstable(feature = "downcast_unchecked", issue = "90850")]
321     #[inline]
322     pub unsafe fn downcast_mut_unchecked<T: Any>(&mut self) -> &mut T {
323         debug_assert!(self.is::<T>());
324         // SAFETY: caller guarantees that T is the correct type
325         unsafe { &mut *(self as *mut dyn Any as *mut T) }
326     }
327 }
328
329 impl dyn Any + Send {
330     /// Forwards to the method defined on the type `dyn Any`.
331     ///
332     /// # Examples
333     ///
334     /// ```
335     /// use std::any::Any;
336     ///
337     /// fn is_string(s: &(dyn Any + Send)) {
338     ///     if s.is::<String>() {
339     ///         println!("It's a string!");
340     ///     } else {
341     ///         println!("Not a string...");
342     ///     }
343     /// }
344     ///
345     /// is_string(&0);
346     /// is_string(&"cookie monster".to_string());
347     /// ```
348     #[stable(feature = "rust1", since = "1.0.0")]
349     #[inline]
350     pub fn is<T: Any>(&self) -> bool {
351         <dyn Any>::is::<T>(self)
352     }
353
354     /// Forwards to the method defined on the type `dyn Any`.
355     ///
356     /// # Examples
357     ///
358     /// ```
359     /// use std::any::Any;
360     ///
361     /// fn print_if_string(s: &(dyn Any + Send)) {
362     ///     if let Some(string) = s.downcast_ref::<String>() {
363     ///         println!("It's a string({}): '{}'", string.len(), string);
364     ///     } else {
365     ///         println!("Not a string...");
366     ///     }
367     /// }
368     ///
369     /// print_if_string(&0);
370     /// print_if_string(&"cookie monster".to_string());
371     /// ```
372     #[stable(feature = "rust1", since = "1.0.0")]
373     #[inline]
374     pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
375         <dyn Any>::downcast_ref::<T>(self)
376     }
377
378     /// Forwards to the method defined on the type `dyn Any`.
379     ///
380     /// # Examples
381     ///
382     /// ```
383     /// use std::any::Any;
384     ///
385     /// fn modify_if_u32(s: &mut (dyn Any + Send)) {
386     ///     if let Some(num) = s.downcast_mut::<u32>() {
387     ///         *num = 42;
388     ///     }
389     /// }
390     ///
391     /// let mut x = 10u32;
392     /// let mut s = "starlord".to_string();
393     ///
394     /// modify_if_u32(&mut x);
395     /// modify_if_u32(&mut s);
396     ///
397     /// assert_eq!(x, 42);
398     /// assert_eq!(&s, "starlord");
399     /// ```
400     #[stable(feature = "rust1", since = "1.0.0")]
401     #[inline]
402     pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
403         <dyn Any>::downcast_mut::<T>(self)
404     }
405
406     /// Forwards to the method defined on the type `dyn Any`.
407     ///
408     /// # Examples
409     ///
410     /// ```
411     /// #![feature(downcast_unchecked)]
412     ///
413     /// use std::any::Any;
414     ///
415     /// let x: Box<dyn Any> = Box::new(1_usize);
416     ///
417     /// unsafe {
418     ///     assert_eq!(*x.downcast_ref_unchecked::<usize>(), 1);
419     /// }
420     /// ```
421     ///
422     /// # Safety
423     ///
424     /// Same as the method on the type `dyn Any`.
425     #[unstable(feature = "downcast_unchecked", issue = "90850")]
426     #[inline]
427     pub unsafe fn downcast_ref_unchecked<T: Any>(&self) -> &T {
428         // SAFETY: guaranteed by caller
429         unsafe { <dyn Any>::downcast_ref_unchecked::<T>(self) }
430     }
431
432     /// Forwards to the method defined on the type `dyn Any`.
433     ///
434     /// # Examples
435     ///
436     /// ```
437     /// #![feature(downcast_unchecked)]
438     ///
439     /// use std::any::Any;
440     ///
441     /// let mut x: Box<dyn Any> = Box::new(1_usize);
442     ///
443     /// unsafe {
444     ///     *x.downcast_mut_unchecked::<usize>() += 1;
445     /// }
446     ///
447     /// assert_eq!(*x.downcast_ref::<usize>().unwrap(), 2);
448     /// ```
449     ///
450     /// # Safety
451     ///
452     /// Same as the method on the type `dyn Any`.
453     #[unstable(feature = "downcast_unchecked", issue = "90850")]
454     #[inline]
455     pub unsafe fn downcast_mut_unchecked<T: Any>(&mut self) -> &mut T {
456         // SAFETY: guaranteed by caller
457         unsafe { <dyn Any>::downcast_mut_unchecked::<T>(self) }
458     }
459 }
460
461 impl dyn Any + Send + Sync {
462     /// Forwards to the method defined on the type `Any`.
463     ///
464     /// # Examples
465     ///
466     /// ```
467     /// use std::any::Any;
468     ///
469     /// fn is_string(s: &(dyn Any + Send + Sync)) {
470     ///     if s.is::<String>() {
471     ///         println!("It's a string!");
472     ///     } else {
473     ///         println!("Not a string...");
474     ///     }
475     /// }
476     ///
477     /// is_string(&0);
478     /// is_string(&"cookie monster".to_string());
479     /// ```
480     #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
481     #[inline]
482     pub fn is<T: Any>(&self) -> bool {
483         <dyn Any>::is::<T>(self)
484     }
485
486     /// Forwards to the method defined on the type `Any`.
487     ///
488     /// # Examples
489     ///
490     /// ```
491     /// use std::any::Any;
492     ///
493     /// fn print_if_string(s: &(dyn Any + Send + Sync)) {
494     ///     if let Some(string) = s.downcast_ref::<String>() {
495     ///         println!("It's a string({}): '{}'", string.len(), string);
496     ///     } else {
497     ///         println!("Not a string...");
498     ///     }
499     /// }
500     ///
501     /// print_if_string(&0);
502     /// print_if_string(&"cookie monster".to_string());
503     /// ```
504     #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
505     #[inline]
506     pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
507         <dyn Any>::downcast_ref::<T>(self)
508     }
509
510     /// Forwards to the method defined on the type `Any`.
511     ///
512     /// # Examples
513     ///
514     /// ```
515     /// use std::any::Any;
516     ///
517     /// fn modify_if_u32(s: &mut (dyn Any + Send + Sync)) {
518     ///     if let Some(num) = s.downcast_mut::<u32>() {
519     ///         *num = 42;
520     ///     }
521     /// }
522     ///
523     /// let mut x = 10u32;
524     /// let mut s = "starlord".to_string();
525     ///
526     /// modify_if_u32(&mut x);
527     /// modify_if_u32(&mut s);
528     ///
529     /// assert_eq!(x, 42);
530     /// assert_eq!(&s, "starlord");
531     /// ```
532     #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
533     #[inline]
534     pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
535         <dyn Any>::downcast_mut::<T>(self)
536     }
537
538     /// Forwards to the method defined on the type `Any`.
539     ///
540     /// # Examples
541     ///
542     /// ```
543     /// #![feature(downcast_unchecked)]
544     ///
545     /// use std::any::Any;
546     ///
547     /// let x: Box<dyn Any> = Box::new(1_usize);
548     ///
549     /// unsafe {
550     ///     assert_eq!(*x.downcast_ref_unchecked::<usize>(), 1);
551     /// }
552     /// ```
553     #[unstable(feature = "downcast_unchecked", issue = "90850")]
554     #[inline]
555     pub unsafe fn downcast_ref_unchecked<T: Any>(&self) -> &T {
556         // SAFETY: guaranteed by caller
557         unsafe { <dyn Any>::downcast_ref_unchecked::<T>(self) }
558     }
559
560     /// Forwards to the method defined on the type `Any`.
561     ///
562     /// # Examples
563     ///
564     /// ```
565     /// #![feature(downcast_unchecked)]
566     ///
567     /// use std::any::Any;
568     ///
569     /// let mut x: Box<dyn Any> = Box::new(1_usize);
570     ///
571     /// unsafe {
572     ///     *x.downcast_mut_unchecked::<usize>() += 1;
573     /// }
574     ///
575     /// assert_eq!(*x.downcast_ref::<usize>().unwrap(), 2);
576     /// ```
577     #[unstable(feature = "downcast_unchecked", issue = "90850")]
578     #[inline]
579     pub unsafe fn downcast_mut_unchecked<T: Any>(&mut self) -> &mut T {
580         // SAFETY: guaranteed by caller
581         unsafe { <dyn Any>::downcast_mut_unchecked::<T>(self) }
582     }
583 }
584
585 ///////////////////////////////////////////////////////////////////////////////
586 // TypeID and its methods
587 ///////////////////////////////////////////////////////////////////////////////
588
589 /// A `TypeId` represents a globally unique identifier for a type.
590 ///
591 /// Each `TypeId` is an opaque object which does not allow inspection of what's
592 /// inside but does allow basic operations such as cloning, comparison,
593 /// printing, and showing.
594 ///
595 /// A `TypeId` is currently only available for types which ascribe to `'static`,
596 /// but this limitation may be removed in the future.
597 ///
598 /// While `TypeId` implements `Hash`, `PartialOrd`, and `Ord`, it is worth
599 /// noting that the hashes and ordering will vary between Rust releases. Beware
600 /// of relying on them inside of your code!
601 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
602 #[stable(feature = "rust1", since = "1.0.0")]
603 pub struct TypeId {
604     t: u64,
605 }
606
607 impl TypeId {
608     /// Returns the `TypeId` of the type this generic function has been
609     /// instantiated with.
610     ///
611     /// # Examples
612     ///
613     /// ```
614     /// use std::any::{Any, TypeId};
615     ///
616     /// fn is_string<T: ?Sized + Any>(_s: &T) -> bool {
617     ///     TypeId::of::<String>() == TypeId::of::<T>()
618     /// }
619     ///
620     /// assert_eq!(is_string(&0), false);
621     /// assert_eq!(is_string(&"cookie monster".to_string()), true);
622     /// ```
623     #[must_use]
624     #[stable(feature = "rust1", since = "1.0.0")]
625     #[rustc_const_unstable(feature = "const_type_id", issue = "77125")]
626     pub const fn of<T: ?Sized + 'static>() -> TypeId {
627         TypeId { t: intrinsics::type_id::<T>() }
628     }
629 }
630
631 /// Returns the name of a type as a string slice.
632 ///
633 /// # Note
634 ///
635 /// This is intended for diagnostic use. The exact contents and format of the
636 /// string returned are not specified, other than being a best-effort
637 /// description of the type. For example, amongst the strings
638 /// that `type_name::<Option<String>>()` might return are `"Option<String>"` and
639 /// `"std::option::Option<std::string::String>"`.
640 ///
641 /// The returned string must not be considered to be a unique identifier of a
642 /// type as multiple types may map to the same type name. Similarly, there is no
643 /// guarantee that all parts of a type will appear in the returned string: for
644 /// example, lifetime specifiers are currently not included. In addition, the
645 /// output may change between versions of the compiler.
646 ///
647 /// The current implementation uses the same infrastructure as compiler
648 /// diagnostics and debuginfo, but this is not guaranteed.
649 ///
650 /// # Examples
651 ///
652 /// ```rust
653 /// assert_eq!(
654 ///     std::any::type_name::<Option<String>>(),
655 ///     "core::option::Option<alloc::string::String>",
656 /// );
657 /// ```
658 #[must_use]
659 #[stable(feature = "type_name", since = "1.38.0")]
660 #[rustc_const_unstable(feature = "const_type_name", issue = "63084")]
661 pub const fn type_name<T: ?Sized>() -> &'static str {
662     intrinsics::type_name::<T>()
663 }
664
665 /// Returns the name of the type of the pointed-to value as a string slice.
666 /// This is the same as `type_name::<T>()`, but can be used where the type of a
667 /// variable is not easily available.
668 ///
669 /// # Note
670 ///
671 /// This is intended for diagnostic use. The exact contents and format of the
672 /// string are not specified, other than being a best-effort description of the
673 /// type. For example, `type_name_of_val::<Option<String>>(None)` could return
674 /// `"Option<String>"` or `"std::option::Option<std::string::String>"`, but not
675 /// `"foobar"`. In addition, the output may change between versions of the
676 /// compiler.
677 ///
678 /// This function does not resolve trait objects,
679 /// meaning that `type_name_of_val(&7u32 as &dyn Debug)`
680 /// may return `"dyn Debug"`, but not `"u32"`.
681 ///
682 /// The type name should not be considered a unique identifier of a type;
683 /// multiple types may share the same type name.
684 ///
685 /// The current implementation uses the same infrastructure as compiler
686 /// diagnostics and debuginfo, but this is not guaranteed.
687 ///
688 /// # Examples
689 ///
690 /// Prints the default integer and float types.
691 ///
692 /// ```rust
693 /// #![feature(type_name_of_val)]
694 /// use std::any::type_name_of_val;
695 ///
696 /// let x = 1;
697 /// println!("{}", type_name_of_val(&x));
698 /// let y = 1.0;
699 /// println!("{}", type_name_of_val(&y));
700 /// ```
701 #[must_use]
702 #[unstable(feature = "type_name_of_val", issue = "66359")]
703 #[rustc_const_unstable(feature = "const_type_name", issue = "63084")]
704 pub const fn type_name_of_val<T: ?Sized>(_val: &T) -> &'static str {
705     type_name::<T>()
706 }