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
19 //! Consider a situation where we want to log out a value passed to a function.
20 //! We know the value we're working on implements Debug, but we don't know its
21 //! concrete type. We want to give special treatment to certain types: in this
22 //! case printing out the length of String values prior to their value.
23 //! We don't know the concrete type of our value at compile time, so we need to
24 //! use runtime reflection instead.
27 //! use std::fmt::Debug;
28 //! use std::any::Any;
30 //! // Logger function for any type that implements Debug.
31 //! fn log<T: Any + Debug>(value: &T) {
32 //! let value_any = value as &dyn Any;
34 //! // Try to convert our value to a `String`. If successful, we want to
35 //! // output the String`'s length as well as its value. If not, it's a
36 //! // different type: just print it out unadorned.
37 //! match value_any.downcast_ref::<String>() {
38 //! Some(as_string) => {
39 //! println!("String ({}): {}", as_string.len(), as_string);
42 //! println!("{:?}", value);
47 //! // This function wants to log its parameter out prior to doing work with it.
48 //! fn do_work<T: Any + Debug>(value: &T) {
50 //! // ...do some other work
54 //! let my_string = "Hello World".to_string();
55 //! do_work(&my_string);
57 //! let my_i8: i8 = 100;
62 #![stable(feature = "rust1", since = "1.0.0")]
65 use crate::intrinsics;
67 ///////////////////////////////////////////////////////////////////////////////
69 ///////////////////////////////////////////////////////////////////////////////
71 /// A trait to emulate dynamic typing.
73 /// Most types implement `Any`. However, any type which contains a non-`'static` reference does not.
74 /// See the [module-level documentation][mod] for more details.
77 #[stable(feature = "rust1", since = "1.0.0")]
78 pub trait Any: 'static {
79 /// Gets the `TypeId` of `self`.
84 /// use std::any::{Any, TypeId};
86 /// fn is_string(s: &dyn Any) -> bool {
87 /// TypeId::of::<String>() == s.type_id()
90 /// assert_eq!(is_string(&0), false);
91 /// assert_eq!(is_string(&"cookie monster".to_string()), true);
93 #[stable(feature = "get_type_id", since = "1.34.0")]
94 fn type_id(&self) -> TypeId;
97 #[stable(feature = "rust1", since = "1.0.0")]
98 impl<T: 'static + ?Sized > Any for T {
99 fn type_id(&self) -> TypeId { TypeId::of::<T>() }
102 ///////////////////////////////////////////////////////////////////////////////
103 // Extension methods for Any trait objects.
104 ///////////////////////////////////////////////////////////////////////////////
106 #[stable(feature = "rust1", since = "1.0.0")]
107 impl fmt::Debug for dyn Any {
108 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
113 // Ensure that the result of e.g., joining a thread can be printed and
114 // hence used with `unwrap`. May eventually no longer be needed if
115 // dispatch works with upcasting.
116 #[stable(feature = "rust1", since = "1.0.0")]
117 impl fmt::Debug for dyn Any + Send {
118 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
123 #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
124 impl fmt::Debug for dyn Any + Send + Sync {
125 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
131 /// Returns `true` if the boxed type is the same as `T`.
136 /// use std::any::Any;
138 /// fn is_string(s: &dyn Any) {
139 /// if s.is::<String>() {
140 /// println!("It's a string!");
142 /// println!("Not a string...");
147 /// is_string(&"cookie monster".to_string());
149 #[stable(feature = "rust1", since = "1.0.0")]
151 pub fn is<T: Any>(&self) -> bool {
152 // Get `TypeId` of the type this function is instantiated with.
153 let t = TypeId::of::<T>();
155 // Get `TypeId` of the type in the trait object.
156 let concrete = self.type_id();
158 // Compare both `TypeId`s on equality.
162 /// Returns some reference to the boxed value if it is of type `T`, or
163 /// `None` if it isn't.
168 /// use std::any::Any;
170 /// fn print_if_string(s: &dyn Any) {
171 /// if let Some(string) = s.downcast_ref::<String>() {
172 /// println!("It's a string({}): '{}'", string.len(), string);
174 /// println!("Not a string...");
178 /// print_if_string(&0);
179 /// print_if_string(&"cookie monster".to_string());
181 #[stable(feature = "rust1", since = "1.0.0")]
183 pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
185 // SAFETY: just checked whether we are pointing to the correct type
187 Some(&*(self as *const dyn Any as *const T))
194 /// Returns some mutable reference to the boxed value if it is of type `T`, or
195 /// `None` if it isn't.
200 /// use std::any::Any;
202 /// fn modify_if_u32(s: &mut dyn Any) {
203 /// if let Some(num) = s.downcast_mut::<u32>() {
208 /// let mut x = 10u32;
209 /// let mut s = "starlord".to_string();
211 /// modify_if_u32(&mut x);
212 /// modify_if_u32(&mut s);
214 /// assert_eq!(x, 42);
215 /// assert_eq!(&s, "starlord");
217 #[stable(feature = "rust1", since = "1.0.0")]
219 pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
221 // SAFETY: just checked whether we are pointing to the correct type
223 Some(&mut *(self as *mut dyn Any as *mut T))
232 /// Forwards to the method defined on the type `Any`.
237 /// use std::any::Any;
239 /// fn is_string(s: &(dyn Any + Send)) {
240 /// if s.is::<String>() {
241 /// println!("It's a string!");
243 /// println!("Not a string...");
248 /// is_string(&"cookie monster".to_string());
250 #[stable(feature = "rust1", since = "1.0.0")]
252 pub fn is<T: Any>(&self) -> bool {
256 /// Forwards to the method defined on the type `Any`.
261 /// use std::any::Any;
263 /// fn print_if_string(s: &(dyn Any + Send)) {
264 /// if let Some(string) = s.downcast_ref::<String>() {
265 /// println!("It's a string({}): '{}'", string.len(), string);
267 /// println!("Not a string...");
271 /// print_if_string(&0);
272 /// print_if_string(&"cookie monster".to_string());
274 #[stable(feature = "rust1", since = "1.0.0")]
276 pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
277 Any::downcast_ref::<T>(self)
280 /// Forwards to the method defined on the type `Any`.
285 /// use std::any::Any;
287 /// fn modify_if_u32(s: &mut (dyn Any + Send)) {
288 /// if let Some(num) = s.downcast_mut::<u32>() {
293 /// let mut x = 10u32;
294 /// let mut s = "starlord".to_string();
296 /// modify_if_u32(&mut x);
297 /// modify_if_u32(&mut s);
299 /// assert_eq!(x, 42);
300 /// assert_eq!(&s, "starlord");
302 #[stable(feature = "rust1", since = "1.0.0")]
304 pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
305 Any::downcast_mut::<T>(self)
309 impl dyn Any+Send+Sync {
310 /// Forwards to the method defined on the type `Any`.
315 /// use std::any::Any;
317 /// fn is_string(s: &(dyn Any + Send + Sync)) {
318 /// if s.is::<String>() {
319 /// println!("It's a string!");
321 /// println!("Not a string...");
326 /// is_string(&"cookie monster".to_string());
328 #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
330 pub fn is<T: Any>(&self) -> bool {
334 /// Forwards to the method defined on the type `Any`.
339 /// use std::any::Any;
341 /// fn print_if_string(s: &(dyn Any + Send + Sync)) {
342 /// if let Some(string) = s.downcast_ref::<String>() {
343 /// println!("It's a string({}): '{}'", string.len(), string);
345 /// println!("Not a string...");
349 /// print_if_string(&0);
350 /// print_if_string(&"cookie monster".to_string());
352 #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
354 pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
355 Any::downcast_ref::<T>(self)
358 /// Forwards to the method defined on the type `Any`.
363 /// use std::any::Any;
365 /// fn modify_if_u32(s: &mut (dyn Any + Send + Sync)) {
366 /// if let Some(num) = s.downcast_mut::<u32>() {
371 /// let mut x = 10u32;
372 /// let mut s = "starlord".to_string();
374 /// modify_if_u32(&mut x);
375 /// modify_if_u32(&mut s);
377 /// assert_eq!(x, 42);
378 /// assert_eq!(&s, "starlord");
380 #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
382 pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
383 Any::downcast_mut::<T>(self)
387 ///////////////////////////////////////////////////////////////////////////////
388 // TypeID and its methods
389 ///////////////////////////////////////////////////////////////////////////////
391 /// A `TypeId` represents a globally unique identifier for a type.
393 /// Each `TypeId` is an opaque object which does not allow inspection of what's
394 /// inside but does allow basic operations such as cloning, comparison,
395 /// printing, and showing.
397 /// A `TypeId` is currently only available for types which ascribe to `'static`,
398 /// but this limitation may be removed in the future.
400 /// While `TypeId` implements `Hash`, `PartialOrd`, and `Ord`, it is worth
401 /// noting that the hashes and ordering will vary between Rust releases. Beware
402 /// of relying on them inside of your code!
403 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
404 #[stable(feature = "rust1", since = "1.0.0")]
410 /// Returns the `TypeId` of the type this generic function has been
411 /// instantiated with.
416 /// use std::any::{Any, TypeId};
418 /// fn is_string<T: ?Sized + Any>(_s: &T) -> bool {
419 /// TypeId::of::<String>() == TypeId::of::<T>()
422 /// assert_eq!(is_string(&0), false);
423 /// assert_eq!(is_string(&"cookie monster".to_string()), true);
425 #[stable(feature = "rust1", since = "1.0.0")]
426 #[rustc_const_unstable(feature="const_type_id")]
427 pub const fn of<T: ?Sized + 'static>() -> TypeId {
430 // SAFETY: going away soon
431 t: unsafe { intrinsics::type_id::<T>() },
432 #[cfg(not(bootstrap))]
433 t: intrinsics::type_id::<T>(),
438 /// Returns the name of a type as a string slice.
442 /// This is intended for diagnostic use. The exact contents and format of the
443 /// string are not specified, other than being a best-effort description of the
444 /// type. For example, `type_name::<Option<String>>()` could return the
445 /// `"Option<String>"` or `"std::option::Option<std::string::String>"`, but not
446 /// `"foobar"`. In addition, the output may change between versions of the
449 /// The type name should not be considered a unique identifier of a type;
450 /// multiple types may share the same type name.
452 /// The current implementation uses the same infrastructure as compiler
453 /// diagnostics and debuginfo, but this is not guaranteed.
459 /// std::any::type_name::<Option<String>>(),
460 /// "core::option::Option<alloc::string::String>",
463 #[stable(feature = "type_name", since = "1.38.0")]
464 #[rustc_const_unstable(feature = "const_type_name")]
465 pub const fn type_name<T: ?Sized>() -> &'static str {
466 intrinsics::type_name::<T>()
469 /// Returns the name of the type of the pointed-to value as a string slice.
470 /// This is the same as `type_name::<T>()`, but can be used where the type of a
471 /// variable is not easily available.
475 /// This is intended for diagnostic use. The exact contents and format of the
476 /// string are not specified, other than being a best-effort description of the
477 /// type. For example, `type_name_of::<Option<String>>(None)` could return the
478 /// `"Option<String>"` or `"std::option::Option<std::string::String>"`, but not
479 /// `"foobar"`. In addition, the output may change between versions of the
482 /// The type name should not be considered a unique identifier of a type;
483 /// multiple types may share the same type name.
485 /// The current implementation uses the same infrastructure as compiler
486 /// diagnostics and debuginfo, but this is not guaranteed.
490 /// Prints the default integer and float types.
493 /// #![feature(type_name_of_val)]
494 /// use std::any::type_name_of_val;
497 /// println!("{}", type_name_of_val(&x));
499 /// println!("{}", type_name_of_val(&y));
501 #[unstable(feature = "type_name_of_val", issue = "66359")]
502 #[rustc_const_unstable(feature = "const_type_name")]
503 pub const fn type_name_of_val<T: ?Sized>(val: &T) -> &'static str {