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")]
type_id(&self) -> TypeId128     fn type_id(&self) -> TypeId;
129 }
130 
131 #[stable(feature = "rust1", since = "1.0.0")]
132 impl<T: 'static + ?Sized> Any for T {
type_id(&self) -> TypeId133     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 {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result144     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 {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result154     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 {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result161     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 boxed 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]
is<T: Any>(&self) -> bool187     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 boxed 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]
downcast_ref<T: Any>(&self) -> Option<&T>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 as *const dyn Any as *const T)) }
225         } else {
226             None
227         }
228     }
229 
230     /// Returns some mutable reference to the boxed 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]
downcast_mut<T: Any>(&mut self) -> Option<&mut T>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(&mut *(self as *mut dyn Any as *mut T)) }
261         } else {
262             None
263         }
264     }
265 }
266 
267 impl dyn Any + Send {
268     /// Forwards to the method defined on the type `Any`.
269     ///
270     /// # Examples
271     ///
272     /// ```
273     /// use std::any::Any;
274     ///
275     /// fn is_string(s: &(dyn Any + Send)) {
276     ///     if s.is::<String>() {
277     ///         println!("It's a string!");
278     ///     } else {
279     ///         println!("Not a string...");
280     ///     }
281     /// }
282     ///
283     /// is_string(&0);
284     /// is_string(&"cookie monster".to_string());
285     /// ```
286     #[stable(feature = "rust1", since = "1.0.0")]
287     #[inline]
is<T: Any>(&self) -> bool288     pub fn is<T: Any>(&self) -> bool {
289         <dyn Any>::is::<T>(self)
290     }
291 
292     /// Forwards to the method defined on the type `Any`.
293     ///
294     /// # Examples
295     ///
296     /// ```
297     /// use std::any::Any;
298     ///
299     /// fn print_if_string(s: &(dyn Any + Send)) {
300     ///     if let Some(string) = s.downcast_ref::<String>() {
301     ///         println!("It's a string({}): '{}'", string.len(), string);
302     ///     } else {
303     ///         println!("Not a string...");
304     ///     }
305     /// }
306     ///
307     /// print_if_string(&0);
308     /// print_if_string(&"cookie monster".to_string());
309     /// ```
310     #[stable(feature = "rust1", since = "1.0.0")]
311     #[inline]
downcast_ref<T: Any>(&self) -> Option<&T>312     pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
313         <dyn Any>::downcast_ref::<T>(self)
314     }
315 
316     /// Forwards to the method defined on the type `Any`.
317     ///
318     /// # Examples
319     ///
320     /// ```
321     /// use std::any::Any;
322     ///
323     /// fn modify_if_u32(s: &mut (dyn Any + Send)) {
324     ///     if let Some(num) = s.downcast_mut::<u32>() {
325     ///         *num = 42;
326     ///     }
327     /// }
328     ///
329     /// let mut x = 10u32;
330     /// let mut s = "starlord".to_string();
331     ///
332     /// modify_if_u32(&mut x);
333     /// modify_if_u32(&mut s);
334     ///
335     /// assert_eq!(x, 42);
336     /// assert_eq!(&s, "starlord");
337     /// ```
338     #[stable(feature = "rust1", since = "1.0.0")]
339     #[inline]
downcast_mut<T: Any>(&mut self) -> Option<&mut T>340     pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
341         <dyn Any>::downcast_mut::<T>(self)
342     }
343 }
344 
345 impl dyn Any + Send + Sync {
346     /// Forwards to the method defined on the type `Any`.
347     ///
348     /// # Examples
349     ///
350     /// ```
351     /// use std::any::Any;
352     ///
353     /// fn is_string(s: &(dyn Any + Send + Sync)) {
354     ///     if s.is::<String>() {
355     ///         println!("It's a string!");
356     ///     } else {
357     ///         println!("Not a string...");
358     ///     }
359     /// }
360     ///
361     /// is_string(&0);
362     /// is_string(&"cookie monster".to_string());
363     /// ```
364     #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
365     #[inline]
is<T: Any>(&self) -> bool366     pub fn is<T: Any>(&self) -> bool {
367         <dyn Any>::is::<T>(self)
368     }
369 
370     /// Forwards to the method defined on the type `Any`.
371     ///
372     /// # Examples
373     ///
374     /// ```
375     /// use std::any::Any;
376     ///
377     /// fn print_if_string(s: &(dyn Any + Send + Sync)) {
378     ///     if let Some(string) = s.downcast_ref::<String>() {
379     ///         println!("It's a string({}): '{}'", string.len(), string);
380     ///     } else {
381     ///         println!("Not a string...");
382     ///     }
383     /// }
384     ///
385     /// print_if_string(&0);
386     /// print_if_string(&"cookie monster".to_string());
387     /// ```
388     #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
389     #[inline]
downcast_ref<T: Any>(&self) -> Option<&T>390     pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
391         <dyn Any>::downcast_ref::<T>(self)
392     }
393 
394     /// Forwards to the method defined on the type `Any`.
395     ///
396     /// # Examples
397     ///
398     /// ```
399     /// use std::any::Any;
400     ///
401     /// fn modify_if_u32(s: &mut (dyn Any + Send + Sync)) {
402     ///     if let Some(num) = s.downcast_mut::<u32>() {
403     ///         *num = 42;
404     ///     }
405     /// }
406     ///
407     /// let mut x = 10u32;
408     /// let mut s = "starlord".to_string();
409     ///
410     /// modify_if_u32(&mut x);
411     /// modify_if_u32(&mut s);
412     ///
413     /// assert_eq!(x, 42);
414     /// assert_eq!(&s, "starlord");
415     /// ```
416     #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
417     #[inline]
downcast_mut<T: Any>(&mut self) -> Option<&mut T>418     pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
419         <dyn Any>::downcast_mut::<T>(self)
420     }
421 }
422 
423 ///////////////////////////////////////////////////////////////////////////////
424 // TypeID and its methods
425 ///////////////////////////////////////////////////////////////////////////////
426 
427 /// A `TypeId` represents a globally unique identifier for a type.
428 ///
429 /// Each `TypeId` is an opaque object which does not allow inspection of what's
430 /// inside but does allow basic operations such as cloning, comparison,
431 /// printing, and showing.
432 ///
433 /// A `TypeId` is currently only available for types which ascribe to `'static`,
434 /// but this limitation may be removed in the future.
435 ///
436 /// While `TypeId` implements `Hash`, `PartialOrd`, and `Ord`, it is worth
437 /// noting that the hashes and ordering will vary between Rust releases. Beware
438 /// of relying on them inside of your code!
439 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
440 #[stable(feature = "rust1", since = "1.0.0")]
441 pub struct TypeId {
442     t: u64,
443 }
444 
445 impl TypeId {
446     /// Returns the `TypeId` of the type this generic function has been
447     /// instantiated with.
448     ///
449     /// # Examples
450     ///
451     /// ```
452     /// use std::any::{Any, TypeId};
453     ///
454     /// fn is_string<T: ?Sized + Any>(_s: &T) -> bool {
455     ///     TypeId::of::<String>() == TypeId::of::<T>()
456     /// }
457     ///
458     /// assert_eq!(is_string(&0), false);
459     /// assert_eq!(is_string(&"cookie monster".to_string()), true);
460     /// ```
461     #[must_use]
462     #[stable(feature = "rust1", since = "1.0.0")]
463     #[rustc_const_unstable(feature = "const_type_id", issue = "77125")]
of<T: ?Sized + 'static>() -> TypeId464     pub const fn of<T: ?Sized + 'static>() -> TypeId {
465         TypeId { t: intrinsics::type_id::<T>() }
466     }
467 }
468 
469 /// Returns the name of a type as a string slice.
470 ///
471 /// # Note
472 ///
473 /// This is intended for diagnostic use. The exact contents and format of the
474 /// string returned are not specified, other than being a best-effort
475 /// description of the type. For example, amongst the strings
476 /// that `type_name::<Option<String>>()` might return are `"Option<String>"` and
477 /// `"std::option::Option<std::string::String>"`.
478 ///
479 /// The returned string must not be considered to be a unique identifier of a
480 /// type as multiple types may map to the same type name. Similarly, there is no
481 /// guarantee that all parts of a type will appear in the returned string: for
482 /// example, lifetime specifiers are currently not included. In addition, the
483 /// output may change between versions of the compiler.
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 /// ```rust
491 /// assert_eq!(
492 ///     std::any::type_name::<Option<String>>(),
493 ///     "core::option::Option<alloc::string::String>",
494 /// );
495 /// ```
496 #[must_use]
497 #[stable(feature = "type_name", since = "1.38.0")]
498 #[rustc_const_unstable(feature = "const_type_name", issue = "63084")]
type_name<T: ?Sized>() -> &'static str499 pub const fn type_name<T: ?Sized>() -> &'static str {
500     intrinsics::type_name::<T>()
501 }
502 
503 /// Returns the name of the type of the pointed-to value as a string slice.
504 /// This is the same as `type_name::<T>()`, but can be used where the type of a
505 /// variable is not easily available.
506 ///
507 /// # Note
508 ///
509 /// This is intended for diagnostic use. The exact contents and format of the
510 /// string are not specified, other than being a best-effort description of the
511 /// type. For example, `type_name_of_val::<Option<String>>(None)` could return
512 /// `"Option<String>"` or `"std::option::Option<std::string::String>"`, but not
513 /// `"foobar"`. In addition, the output may change between versions of the
514 /// compiler.
515 ///
516 /// This function does not resolve trait objects,
517 /// meaning that `type_name_of_val(&7u32 as &dyn Debug)`
518 /// may return `"dyn Debug"`, but not `"u32"`.
519 ///
520 /// The type name should not be considered a unique identifier of a type;
521 /// multiple types may share the same type name.
522 ///
523 /// The current implementation uses the same infrastructure as compiler
524 /// diagnostics and debuginfo, but this is not guaranteed.
525 ///
526 /// # Examples
527 ///
528 /// Prints the default integer and float types.
529 ///
530 /// ```rust
531 /// #![feature(type_name_of_val)]
532 /// use std::any::type_name_of_val;
533 ///
534 /// let x = 1;
535 /// println!("{}", type_name_of_val(&x));
536 /// let y = 1.0;
537 /// println!("{}", type_name_of_val(&y));
538 /// ```
539 #[must_use]
540 #[unstable(feature = "type_name_of_val", issue = "66359")]
541 #[rustc_const_unstable(feature = "const_type_name", issue = "63084")]
type_name_of_val<T: ?Sized>(_val: &T) -> &'static str542 pub const fn type_name_of_val<T: ?Sized>(_val: &T) -> &'static str {
543     type_name::<T>()
544 }
545