1 //! This module implements the `Any` trait, which enables dynamic typing
2 //! of any `'static` type through runtime reflection.
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.
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.
15 //! [`Box`]: ../../std/boxed/struct.Box.html
17 //! # Smart pointers and `dyn Any`
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:
27 //! use std::any::{Any, TypeId};
29 //! let boxed: Box<dyn Any> = Box::new(3_i32);
31 //! // You're more likely to want this:
32 //! let actual_id = (&*boxed).type_id();
34 //! let boxed_id = boxed.type_id();
36 //! assert_eq!(actual_id, TypeId::of::<i32>());
37 //! assert_eq!(boxed_id, TypeId::of::<Box<dyn Any>>());
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.
50 //! use std::fmt::Debug;
51 //! use std::any::Any;
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;
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);
65 //! println!("{:?}", value);
70 //! // This function wants to log its parameter out prior to doing work with it.
71 //! fn do_work<T: Any + Debug>(value: &T) {
73 //! // ...do some other work
77 //! let my_string = "Hello World".to_string();
78 //! do_work(&my_string);
80 //! let my_i8: i8 = 100;
85 #![stable(feature = "rust1", since = "1.0.0")]
88 use crate::intrinsics;
90 ///////////////////////////////////////////////////////////////////////////////
92 ///////////////////////////////////////////////////////////////////////////////
94 /// A trait to emulate dynamic typing.
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.
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`.
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`.
118 /// use std::any::{Any, TypeId};
120 /// fn is_string(s: &dyn Any) -> bool {
121 /// TypeId::of::<String>() == s.type_id()
124 /// assert_eq!(is_string(&0), false);
125 /// assert_eq!(is_string(&"cookie monster".to_string()), true);
127 #[stable(feature = "get_type_id", since = "1.34.0")]
128 fn type_id(&self) -> TypeId;
131 #[stable(feature = "rust1", since = "1.0.0")]
132 impl<T: 'static + ?Sized> Any for T {
133 fn type_id(&self) -> TypeId {
138 ///////////////////////////////////////////////////////////////////////////////
139 // Extension methods for Any trait objects.
140 ///////////////////////////////////////////////////////////////////////////////
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()
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()
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()
167 /// Returns `true` if the inner type is the same as `T`.
172 /// use std::any::Any;
174 /// fn is_string(s: &dyn Any) {
175 /// if s.is::<String>() {
176 /// println!("It's a string!");
178 /// println!("Not a string...");
183 /// is_string(&"cookie monster".to_string());
185 #[stable(feature = "rust1", since = "1.0.0")]
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>();
191 // Get `TypeId` of the type in the trait object (`self`).
192 let concrete = self.type_id();
194 // Compare both `TypeId`s on equality.
198 /// Returns some reference to the inner value if it is of type `T`, or
199 /// `None` if it isn't.
204 /// use std::any::Any;
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);
210 /// println!("Not a string...");
214 /// print_if_string(&0);
215 /// print_if_string(&"cookie monster".to_string());
217 #[stable(feature = "rust1", since = "1.0.0")]
219 pub fn downcast_ref<T: Any>(&self) -> Option<&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()) }
230 /// Returns some mutable reference to the inner value if it is of type `T`, or
231 /// `None` if it isn't.
236 /// use std::any::Any;
238 /// fn modify_if_u32(s: &mut dyn Any) {
239 /// if let Some(num) = s.downcast_mut::<u32>() {
244 /// let mut x = 10u32;
245 /// let mut s = "starlord".to_string();
247 /// modify_if_u32(&mut x);
248 /// modify_if_u32(&mut s);
250 /// assert_eq!(x, 42);
251 /// assert_eq!(&s, "starlord");
253 #[stable(feature = "rust1", since = "1.0.0")]
255 pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut 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()) }
266 /// Returns a reference to the inner value as type `dyn T`.
268 /// For a safe alternative see [`downcast_ref`].
273 /// #![feature(downcast_unchecked)]
275 /// use std::any::Any;
277 /// let x: Box<dyn Any> = Box::new(1_usize);
280 /// assert_eq!(*x.downcast_ref_unchecked::<usize>(), 1);
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")]
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) }
296 /// Returns a mutable reference to the inner value as type `dyn T`.
298 /// For a safe alternative see [`downcast_mut`].
303 /// #![feature(downcast_unchecked)]
305 /// use std::any::Any;
307 /// let mut x: Box<dyn Any> = Box::new(1_usize);
310 /// *x.downcast_mut_unchecked::<usize>() += 1;
313 /// assert_eq!(*x.downcast_ref::<usize>().unwrap(), 2);
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")]
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) }
329 impl dyn Any + Send {
330 /// Forwards to the method defined on the type `dyn Any`.
335 /// use std::any::Any;
337 /// fn is_string(s: &(dyn Any + Send)) {
338 /// if s.is::<String>() {
339 /// println!("It's a string!");
341 /// println!("Not a string...");
346 /// is_string(&"cookie monster".to_string());
348 #[stable(feature = "rust1", since = "1.0.0")]
350 pub fn is<T: Any>(&self) -> bool {
351 <dyn Any>::is::<T>(self)
354 /// Forwards to the method defined on the type `dyn Any`.
359 /// use std::any::Any;
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);
365 /// println!("Not a string...");
369 /// print_if_string(&0);
370 /// print_if_string(&"cookie monster".to_string());
372 #[stable(feature = "rust1", since = "1.0.0")]
374 pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
375 <dyn Any>::downcast_ref::<T>(self)
378 /// Forwards to the method defined on the type `dyn Any`.
383 /// use std::any::Any;
385 /// fn modify_if_u32(s: &mut (dyn Any + Send)) {
386 /// if let Some(num) = s.downcast_mut::<u32>() {
391 /// let mut x = 10u32;
392 /// let mut s = "starlord".to_string();
394 /// modify_if_u32(&mut x);
395 /// modify_if_u32(&mut s);
397 /// assert_eq!(x, 42);
398 /// assert_eq!(&s, "starlord");
400 #[stable(feature = "rust1", since = "1.0.0")]
402 pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
403 <dyn Any>::downcast_mut::<T>(self)
406 /// Forwards to the method defined on the type `dyn Any`.
411 /// #![feature(downcast_unchecked)]
413 /// use std::any::Any;
415 /// let x: Box<dyn Any> = Box::new(1_usize);
418 /// assert_eq!(*x.downcast_ref_unchecked::<usize>(), 1);
424 /// Same as the method on the type `dyn Any`.
425 #[unstable(feature = "downcast_unchecked", issue = "90850")]
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) }
432 /// Forwards to the method defined on the type `dyn Any`.
437 /// #![feature(downcast_unchecked)]
439 /// use std::any::Any;
441 /// let mut x: Box<dyn Any> = Box::new(1_usize);
444 /// *x.downcast_mut_unchecked::<usize>() += 1;
447 /// assert_eq!(*x.downcast_ref::<usize>().unwrap(), 2);
452 /// Same as the method on the type `dyn Any`.
453 #[unstable(feature = "downcast_unchecked", issue = "90850")]
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) }
461 impl dyn Any + Send + Sync {
462 /// Forwards to the method defined on the type `Any`.
467 /// use std::any::Any;
469 /// fn is_string(s: &(dyn Any + Send + Sync)) {
470 /// if s.is::<String>() {
471 /// println!("It's a string!");
473 /// println!("Not a string...");
478 /// is_string(&"cookie monster".to_string());
480 #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
482 pub fn is<T: Any>(&self) -> bool {
483 <dyn Any>::is::<T>(self)
486 /// Forwards to the method defined on the type `Any`.
491 /// use std::any::Any;
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);
497 /// println!("Not a string...");
501 /// print_if_string(&0);
502 /// print_if_string(&"cookie monster".to_string());
504 #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
506 pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
507 <dyn Any>::downcast_ref::<T>(self)
510 /// Forwards to the method defined on the type `Any`.
515 /// use std::any::Any;
517 /// fn modify_if_u32(s: &mut (dyn Any + Send + Sync)) {
518 /// if let Some(num) = s.downcast_mut::<u32>() {
523 /// let mut x = 10u32;
524 /// let mut s = "starlord".to_string();
526 /// modify_if_u32(&mut x);
527 /// modify_if_u32(&mut s);
529 /// assert_eq!(x, 42);
530 /// assert_eq!(&s, "starlord");
532 #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
534 pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
535 <dyn Any>::downcast_mut::<T>(self)
538 /// Forwards to the method defined on the type `Any`.
543 /// #![feature(downcast_unchecked)]
545 /// use std::any::Any;
547 /// let x: Box<dyn Any> = Box::new(1_usize);
550 /// assert_eq!(*x.downcast_ref_unchecked::<usize>(), 1);
553 #[unstable(feature = "downcast_unchecked", issue = "90850")]
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) }
560 /// Forwards to the method defined on the type `Any`.
565 /// #![feature(downcast_unchecked)]
567 /// use std::any::Any;
569 /// let mut x: Box<dyn Any> = Box::new(1_usize);
572 /// *x.downcast_mut_unchecked::<usize>() += 1;
575 /// assert_eq!(*x.downcast_ref::<usize>().unwrap(), 2);
577 #[unstable(feature = "downcast_unchecked", issue = "90850")]
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) }
585 ///////////////////////////////////////////////////////////////////////////////
586 // TypeID and its methods
587 ///////////////////////////////////////////////////////////////////////////////
589 /// A `TypeId` represents a globally unique identifier for a type.
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.
595 /// A `TypeId` is currently only available for types which ascribe to `'static`,
596 /// but this limitation may be removed in the future.
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")]
608 /// Returns the `TypeId` of the type this generic function has been
609 /// instantiated with.
614 /// use std::any::{Any, TypeId};
616 /// fn is_string<T: ?Sized + Any>(_s: &T) -> bool {
617 /// TypeId::of::<String>() == TypeId::of::<T>()
620 /// assert_eq!(is_string(&0), false);
621 /// assert_eq!(is_string(&"cookie monster".to_string()), true);
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>() }
631 /// Returns the name of a type as a string slice.
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>"`.
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.
647 /// The current implementation uses the same infrastructure as compiler
648 /// diagnostics and debuginfo, but this is not guaranteed.
654 /// std::any::type_name::<Option<String>>(),
655 /// "core::option::Option<alloc::string::String>",
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>()
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.
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
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"`.
682 /// The type name should not be considered a unique identifier of a type;
683 /// multiple types may share the same type name.
685 /// The current implementation uses the same infrastructure as compiler
686 /// diagnostics and debuginfo, but this is not guaranteed.
690 /// Prints the default integer and float types.
693 /// #![feature(type_name_of_val)]
694 /// use std::any::type_name_of_val;
697 /// println!("{}", type_name_of_val(&x));
699 /// println!("{}", type_name_of_val(&y));
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 {