]> git.lizzy.rs Git - rust.git/blob - library/core/src/any.rs
Fix two false positive lints
[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     /// # Examples
269     ///
270     /// ```
271     /// #![feature(downcast_unchecked)]
272     ///
273     /// use std::any::Any;
274     ///
275     /// let x: Box<dyn Any> = Box::new(1_usize);
276     ///
277     /// unsafe {
278     ///     assert_eq!(*x.downcast_ref_unchecked::<usize>(), 1);
279     /// }
280     /// ```
281     ///
282     /// # Safety
283     ///
284     /// The contained value must be of type `T`. Calling this method
285     /// with the incorrect type is *undefined behavior*.
286     #[unstable(feature = "downcast_unchecked", issue = "90850")]
287     #[inline]
288     pub unsafe fn downcast_ref_unchecked<T: Any>(&self) -> &T {
289         debug_assert!(self.is::<T>());
290         // SAFETY: caller guarantees that T is the correct type
291         unsafe { &*(self as *const dyn Any as *const T) }
292     }
293
294     /// Returns a mutable reference to the inner value as type `dyn T`.
295     ///
296     /// # Examples
297     ///
298     /// ```
299     /// #![feature(downcast_unchecked)]
300     ///
301     /// use std::any::Any;
302     ///
303     /// let mut x: Box<dyn Any> = Box::new(1_usize);
304     ///
305     /// unsafe {
306     ///     *x.downcast_mut_unchecked::<usize>() += 1;
307     /// }
308     ///
309     /// assert_eq!(*x.downcast_ref::<usize>().unwrap(), 2);
310     /// ```
311     ///
312     /// # Safety
313     ///
314     /// The contained value must be of type `T`. Calling this method
315     /// with the incorrect type is *undefined behavior*.
316     #[unstable(feature = "downcast_unchecked", issue = "90850")]
317     #[inline]
318     pub unsafe fn downcast_mut_unchecked<T: Any>(&mut self) -> &mut T {
319         debug_assert!(self.is::<T>());
320         // SAFETY: caller guarantees that T is the correct type
321         unsafe { &mut *(self as *mut dyn Any as *mut T) }
322     }
323 }
324
325 impl dyn Any + Send {
326     /// Forwards to the method defined on the type `dyn Any`.
327     ///
328     /// # Examples
329     ///
330     /// ```
331     /// use std::any::Any;
332     ///
333     /// fn is_string(s: &(dyn Any + Send)) {
334     ///     if s.is::<String>() {
335     ///         println!("It's a string!");
336     ///     } else {
337     ///         println!("Not a string...");
338     ///     }
339     /// }
340     ///
341     /// is_string(&0);
342     /// is_string(&"cookie monster".to_string());
343     /// ```
344     #[stable(feature = "rust1", since = "1.0.0")]
345     #[inline]
346     pub fn is<T: Any>(&self) -> bool {
347         <dyn Any>::is::<T>(self)
348     }
349
350     /// Forwards to the method defined on the type `dyn Any`.
351     ///
352     /// # Examples
353     ///
354     /// ```
355     /// use std::any::Any;
356     ///
357     /// fn print_if_string(s: &(dyn Any + Send)) {
358     ///     if let Some(string) = s.downcast_ref::<String>() {
359     ///         println!("It's a string({}): '{}'", string.len(), string);
360     ///     } else {
361     ///         println!("Not a string...");
362     ///     }
363     /// }
364     ///
365     /// print_if_string(&0);
366     /// print_if_string(&"cookie monster".to_string());
367     /// ```
368     #[stable(feature = "rust1", since = "1.0.0")]
369     #[inline]
370     pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
371         <dyn Any>::downcast_ref::<T>(self)
372     }
373
374     /// Forwards to the method defined on the type `dyn Any`.
375     ///
376     /// # Examples
377     ///
378     /// ```
379     /// use std::any::Any;
380     ///
381     /// fn modify_if_u32(s: &mut (dyn Any + Send)) {
382     ///     if let Some(num) = s.downcast_mut::<u32>() {
383     ///         *num = 42;
384     ///     }
385     /// }
386     ///
387     /// let mut x = 10u32;
388     /// let mut s = "starlord".to_string();
389     ///
390     /// modify_if_u32(&mut x);
391     /// modify_if_u32(&mut s);
392     ///
393     /// assert_eq!(x, 42);
394     /// assert_eq!(&s, "starlord");
395     /// ```
396     #[stable(feature = "rust1", since = "1.0.0")]
397     #[inline]
398     pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
399         <dyn Any>::downcast_mut::<T>(self)
400     }
401
402     /// Forwards to the method defined on the type `dyn Any`.
403     ///
404     /// # Examples
405     ///
406     /// ```
407     /// #![feature(downcast_unchecked)]
408     ///
409     /// use std::any::Any;
410     ///
411     /// let x: Box<dyn Any> = Box::new(1_usize);
412     ///
413     /// unsafe {
414     ///     assert_eq!(*x.downcast_ref_unchecked::<usize>(), 1);
415     /// }
416     /// ```
417     ///
418     /// # Safety
419     ///
420     /// Same as the method on the type `dyn Any`.
421     #[unstable(feature = "downcast_unchecked", issue = "90850")]
422     #[inline]
423     pub unsafe fn downcast_ref_unchecked<T: Any>(&self) -> &T {
424         // SAFETY: guaranteed by caller
425         unsafe { <dyn Any>::downcast_ref_unchecked::<T>(self) }
426     }
427
428     /// Forwards to the method defined on the type `dyn Any`.
429     ///
430     /// # Examples
431     ///
432     /// ```
433     /// #![feature(downcast_unchecked)]
434     ///
435     /// use std::any::Any;
436     ///
437     /// let mut x: Box<dyn Any> = Box::new(1_usize);
438     ///
439     /// unsafe {
440     ///     *x.downcast_mut_unchecked::<usize>() += 1;
441     /// }
442     ///
443     /// assert_eq!(*x.downcast_ref::<usize>().unwrap(), 2);
444     /// ```
445     ///
446     /// # Safety
447     ///
448     /// Same as the method on the type `dyn Any`.
449     #[unstable(feature = "downcast_unchecked", issue = "90850")]
450     #[inline]
451     pub unsafe fn downcast_mut_unchecked<T: Any>(&mut self) -> &mut T {
452         // SAFETY: guaranteed by caller
453         unsafe { <dyn Any>::downcast_mut_unchecked::<T>(self) }
454     }
455 }
456
457 impl dyn Any + Send + Sync {
458     /// Forwards to the method defined on the type `Any`.
459     ///
460     /// # Examples
461     ///
462     /// ```
463     /// use std::any::Any;
464     ///
465     /// fn is_string(s: &(dyn Any + Send + Sync)) {
466     ///     if s.is::<String>() {
467     ///         println!("It's a string!");
468     ///     } else {
469     ///         println!("Not a string...");
470     ///     }
471     /// }
472     ///
473     /// is_string(&0);
474     /// is_string(&"cookie monster".to_string());
475     /// ```
476     #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
477     #[inline]
478     pub fn is<T: Any>(&self) -> bool {
479         <dyn Any>::is::<T>(self)
480     }
481
482     /// Forwards to the method defined on the type `Any`.
483     ///
484     /// # Examples
485     ///
486     /// ```
487     /// use std::any::Any;
488     ///
489     /// fn print_if_string(s: &(dyn Any + Send + Sync)) {
490     ///     if let Some(string) = s.downcast_ref::<String>() {
491     ///         println!("It's a string({}): '{}'", string.len(), string);
492     ///     } else {
493     ///         println!("Not a string...");
494     ///     }
495     /// }
496     ///
497     /// print_if_string(&0);
498     /// print_if_string(&"cookie monster".to_string());
499     /// ```
500     #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
501     #[inline]
502     pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
503         <dyn Any>::downcast_ref::<T>(self)
504     }
505
506     /// Forwards to the method defined on the type `Any`.
507     ///
508     /// # Examples
509     ///
510     /// ```
511     /// use std::any::Any;
512     ///
513     /// fn modify_if_u32(s: &mut (dyn Any + Send + Sync)) {
514     ///     if let Some(num) = s.downcast_mut::<u32>() {
515     ///         *num = 42;
516     ///     }
517     /// }
518     ///
519     /// let mut x = 10u32;
520     /// let mut s = "starlord".to_string();
521     ///
522     /// modify_if_u32(&mut x);
523     /// modify_if_u32(&mut s);
524     ///
525     /// assert_eq!(x, 42);
526     /// assert_eq!(&s, "starlord");
527     /// ```
528     #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
529     #[inline]
530     pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
531         <dyn Any>::downcast_mut::<T>(self)
532     }
533
534     /// Forwards to the method defined on the type `Any`.
535     ///
536     /// # Examples
537     ///
538     /// ```
539     /// #![feature(downcast_unchecked)]
540     ///
541     /// use std::any::Any;
542     ///
543     /// let x: Box<dyn Any> = Box::new(1_usize);
544     ///
545     /// unsafe {
546     ///     assert_eq!(*x.downcast_ref_unchecked::<usize>(), 1);
547     /// }
548     /// ```
549     #[unstable(feature = "downcast_unchecked", issue = "90850")]
550     #[inline]
551     pub unsafe fn downcast_ref_unchecked<T: Any>(&self) -> &T {
552         // SAFETY: guaranteed by caller
553         unsafe { <dyn Any>::downcast_ref_unchecked::<T>(self) }
554     }
555
556     /// Forwards to the method defined on the type `Any`.
557     ///
558     /// # Examples
559     ///
560     /// ```
561     /// #![feature(downcast_unchecked)]
562     ///
563     /// use std::any::Any;
564     ///
565     /// let mut x: Box<dyn Any> = Box::new(1_usize);
566     ///
567     /// unsafe {
568     ///     *x.downcast_mut_unchecked::<usize>() += 1;
569     /// }
570     ///
571     /// assert_eq!(*x.downcast_ref::<usize>().unwrap(), 2);
572     /// ```
573     #[unstable(feature = "downcast_unchecked", issue = "90850")]
574     #[inline]
575     pub unsafe fn downcast_mut_unchecked<T: Any>(&mut self) -> &mut T {
576         // SAFETY: guaranteed by caller
577         unsafe { <dyn Any>::downcast_mut_unchecked::<T>(self) }
578     }
579 }
580
581 ///////////////////////////////////////////////////////////////////////////////
582 // TypeID and its methods
583 ///////////////////////////////////////////////////////////////////////////////
584
585 /// A `TypeId` represents a globally unique identifier for a type.
586 ///
587 /// Each `TypeId` is an opaque object which does not allow inspection of what's
588 /// inside but does allow basic operations such as cloning, comparison,
589 /// printing, and showing.
590 ///
591 /// A `TypeId` is currently only available for types which ascribe to `'static`,
592 /// but this limitation may be removed in the future.
593 ///
594 /// While `TypeId` implements `Hash`, `PartialOrd`, and `Ord`, it is worth
595 /// noting that the hashes and ordering will vary between Rust releases. Beware
596 /// of relying on them inside of your code!
597 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
598 #[stable(feature = "rust1", since = "1.0.0")]
599 pub struct TypeId {
600     t: u64,
601 }
602
603 impl TypeId {
604     /// Returns the `TypeId` of the type this generic function has been
605     /// instantiated with.
606     ///
607     /// # Examples
608     ///
609     /// ```
610     /// use std::any::{Any, TypeId};
611     ///
612     /// fn is_string<T: ?Sized + Any>(_s: &T) -> bool {
613     ///     TypeId::of::<String>() == TypeId::of::<T>()
614     /// }
615     ///
616     /// assert_eq!(is_string(&0), false);
617     /// assert_eq!(is_string(&"cookie monster".to_string()), true);
618     /// ```
619     #[must_use]
620     #[stable(feature = "rust1", since = "1.0.0")]
621     #[rustc_const_unstable(feature = "const_type_id", issue = "77125")]
622     pub const fn of<T: ?Sized + 'static>() -> TypeId {
623         TypeId { t: intrinsics::type_id::<T>() }
624     }
625 }
626
627 /// Returns the name of a type as a string slice.
628 ///
629 /// # Note
630 ///
631 /// This is intended for diagnostic use. The exact contents and format of the
632 /// string returned are not specified, other than being a best-effort
633 /// description of the type. For example, amongst the strings
634 /// that `type_name::<Option<String>>()` might return are `"Option<String>"` and
635 /// `"std::option::Option<std::string::String>"`.
636 ///
637 /// The returned string must not be considered to be a unique identifier of a
638 /// type as multiple types may map to the same type name. Similarly, there is no
639 /// guarantee that all parts of a type will appear in the returned string: for
640 /// example, lifetime specifiers are currently not included. In addition, the
641 /// output may change between versions of the compiler.
642 ///
643 /// The current implementation uses the same infrastructure as compiler
644 /// diagnostics and debuginfo, but this is not guaranteed.
645 ///
646 /// # Examples
647 ///
648 /// ```rust
649 /// assert_eq!(
650 ///     std::any::type_name::<Option<String>>(),
651 ///     "core::option::Option<alloc::string::String>",
652 /// );
653 /// ```
654 #[must_use]
655 #[stable(feature = "type_name", since = "1.38.0")]
656 #[rustc_const_unstable(feature = "const_type_name", issue = "63084")]
657 pub const fn type_name<T: ?Sized>() -> &'static str {
658     intrinsics::type_name::<T>()
659 }
660
661 /// Returns the name of the type of the pointed-to value as a string slice.
662 /// This is the same as `type_name::<T>()`, but can be used where the type of a
663 /// variable is not easily available.
664 ///
665 /// # Note
666 ///
667 /// This is intended for diagnostic use. The exact contents and format of the
668 /// string are not specified, other than being a best-effort description of the
669 /// type. For example, `type_name_of_val::<Option<String>>(None)` could return
670 /// `"Option<String>"` or `"std::option::Option<std::string::String>"`, but not
671 /// `"foobar"`. In addition, the output may change between versions of the
672 /// compiler.
673 ///
674 /// This function does not resolve trait objects,
675 /// meaning that `type_name_of_val(&7u32 as &dyn Debug)`
676 /// may return `"dyn Debug"`, but not `"u32"`.
677 ///
678 /// The type name should not be considered a unique identifier of a type;
679 /// multiple types may share the same type name.
680 ///
681 /// The current implementation uses the same infrastructure as compiler
682 /// diagnostics and debuginfo, but this is not guaranteed.
683 ///
684 /// # Examples
685 ///
686 /// Prints the default integer and float types.
687 ///
688 /// ```rust
689 /// #![feature(type_name_of_val)]
690 /// use std::any::type_name_of_val;
691 ///
692 /// let x = 1;
693 /// println!("{}", type_name_of_val(&x));
694 /// let y = 1.0;
695 /// println!("{}", type_name_of_val(&y));
696 /// ```
697 #[must_use]
698 #[unstable(feature = "type_name_of_val", issue = "66359")]
699 #[rustc_const_unstable(feature = "const_type_name", issue = "63084")]
700 pub const fn type_name_of_val<T: ?Sized>(_val: &T) -> &'static str {
701     type_name::<T>()
702 }