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 boxed 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 boxed 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 as *const dyn Any as *const T)) }
230 /// Returns some mutable reference to the boxed 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(&mut *(self as *mut dyn Any as *mut T)) }
267 impl dyn Any + Send {
268 /// Forwards to the method defined on the type `Any`.
273 /// use std::any::Any;
275 /// fn is_string(s: &(dyn Any + Send)) {
276 /// if s.is::<String>() {
277 /// println!("It's a string!");
279 /// println!("Not a string...");
284 /// is_string(&"cookie monster".to_string());
286 #[stable(feature = "rust1", since = "1.0.0")]
288 pub fn is<T: Any>(&self) -> bool {
289 <dyn Any>::is::<T>(self)
292 /// Forwards to the method defined on the type `Any`.
297 /// use std::any::Any;
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);
303 /// println!("Not a string...");
307 /// print_if_string(&0);
308 /// print_if_string(&"cookie monster".to_string());
310 #[stable(feature = "rust1", since = "1.0.0")]
312 pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
313 <dyn Any>::downcast_ref::<T>(self)
316 /// Forwards to the method defined on the type `Any`.
321 /// use std::any::Any;
323 /// fn modify_if_u32(s: &mut (dyn Any + Send)) {
324 /// if let Some(num) = s.downcast_mut::<u32>() {
329 /// let mut x = 10u32;
330 /// let mut s = "starlord".to_string();
332 /// modify_if_u32(&mut x);
333 /// modify_if_u32(&mut s);
335 /// assert_eq!(x, 42);
336 /// assert_eq!(&s, "starlord");
338 #[stable(feature = "rust1", since = "1.0.0")]
340 pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
341 <dyn Any>::downcast_mut::<T>(self)
345 impl dyn Any + Send + Sync {
346 /// Forwards to the method defined on the type `Any`.
351 /// use std::any::Any;
353 /// fn is_string(s: &(dyn Any + Send + Sync)) {
354 /// if s.is::<String>() {
355 /// println!("It's a string!");
357 /// println!("Not a string...");
362 /// is_string(&"cookie monster".to_string());
364 #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
366 pub fn is<T: Any>(&self) -> bool {
367 <dyn Any>::is::<T>(self)
370 /// Forwards to the method defined on the type `Any`.
375 /// use std::any::Any;
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);
381 /// println!("Not a string...");
385 /// print_if_string(&0);
386 /// print_if_string(&"cookie monster".to_string());
388 #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
390 pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
391 <dyn Any>::downcast_ref::<T>(self)
394 /// Forwards to the method defined on the type `Any`.
399 /// use std::any::Any;
401 /// fn modify_if_u32(s: &mut (dyn Any + Send + Sync)) {
402 /// if let Some(num) = s.downcast_mut::<u32>() {
407 /// let mut x = 10u32;
408 /// let mut s = "starlord".to_string();
410 /// modify_if_u32(&mut x);
411 /// modify_if_u32(&mut s);
413 /// assert_eq!(x, 42);
414 /// assert_eq!(&s, "starlord");
416 #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
418 pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
419 <dyn Any>::downcast_mut::<T>(self)
423 ///////////////////////////////////////////////////////////////////////////////
424 // TypeID and its methods
425 ///////////////////////////////////////////////////////////////////////////////
427 /// A `TypeId` represents a globally unique identifier for a type.
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.
433 /// A `TypeId` is currently only available for types which ascribe to `'static`,
434 /// but this limitation may be removed in the future.
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")]
446 /// Returns the `TypeId` of the type this generic function has been
447 /// instantiated with.
452 /// use std::any::{Any, TypeId};
454 /// fn is_string<T: ?Sized + Any>(_s: &T) -> bool {
455 /// TypeId::of::<String>() == TypeId::of::<T>()
458 /// assert_eq!(is_string(&0), false);
459 /// assert_eq!(is_string(&"cookie monster".to_string()), true);
461 #[stable(feature = "rust1", since = "1.0.0")]
462 #[rustc_const_unstable(feature = "const_type_id", issue = "77125")]
463 pub const fn of<T: ?Sized + 'static>() -> TypeId {
464 TypeId { t: intrinsics::type_id::<T>() }
468 /// Returns the name of a type as a string slice.
472 /// This is intended for diagnostic use. The exact contents and format of the
473 /// string returned are not specified, other than being a best-effort
474 /// description of the type. For example, amongst the strings
475 /// that `type_name::<Option<String>>()` might return are `"Option<String>"` and
476 /// `"std::option::Option<std::string::String>"`.
478 /// The returned string must not be considered to be a unique identifier of a
479 /// type as multiple types may map to the same type name. Similarly, there is no
480 /// guarantee that all parts of a type will appear in the returned string: for
481 /// example, lifetime specifiers are currently not included. In addition, the
482 /// output may change between versions of the compiler.
484 /// The current implementation uses the same infrastructure as compiler
485 /// diagnostics and debuginfo, but this is not guaranteed.
491 /// std::any::type_name::<Option<String>>(),
492 /// "core::option::Option<alloc::string::String>",
495 #[stable(feature = "type_name", since = "1.38.0")]
496 #[rustc_const_unstable(feature = "const_type_name", issue = "63084")]
497 pub const fn type_name<T: ?Sized>() -> &'static str {
498 intrinsics::type_name::<T>()
501 /// Returns the name of the type of the pointed-to value as a string slice.
502 /// This is the same as `type_name::<T>()`, but can be used where the type of a
503 /// variable is not easily available.
507 /// This is intended for diagnostic use. The exact contents and format of the
508 /// string are not specified, other than being a best-effort description of the
509 /// type. For example, `type_name_of_val::<Option<String>>(None)` could return
510 /// `"Option<String>"` or `"std::option::Option<std::string::String>"`, but not
511 /// `"foobar"`. In addition, the output may change between versions of the
514 /// This function does not resolve trait objects,
515 /// meaning that `type_name_of_val(&7u32 as &dyn Debug)`
516 /// may return `"dyn Debug"`, but not `"u32"`.
518 /// The type name should not be considered a unique identifier of a type;
519 /// multiple types may share the same type name.
521 /// The current implementation uses the same infrastructure as compiler
522 /// diagnostics and debuginfo, but this is not guaranteed.
526 /// Prints the default integer and float types.
529 /// #![feature(type_name_of_val)]
530 /// use std::any::type_name_of_val;
533 /// println!("{}", type_name_of_val(&x));
535 /// println!("{}", type_name_of_val(&y));
537 #[unstable(feature = "type_name_of_val", issue = "66359")]
538 #[rustc_const_unstable(feature = "const_type_name", issue = "63084")]
539 pub const fn type_name_of_val<T: ?Sized>(_val: &T) -> &'static str {