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 // This trait is not unsafe, though we rely on the specifics of it's sole impl's
78 // `type_id` function in unsafe code (e.g., `downcast`). Normally, that would be
79 // a problem, but because the only impl of `Any` is a blanket implementation, no
80 // other code can implement `Any`.
82 // We could plausibly make this trait unsafe -- it would not cause breakage,
83 // since we control all the implementations -- but we choose not to as that's
84 // both not really necessary and may confuse users about the distinction of
85 // unsafe traits and unsafe methods (i.e., `type_id` would still be safe to call,
86 // but we would likely want to indicate as such in documentation).
87 #[stable(feature = "rust1", since = "1.0.0")]
88 pub trait Any: 'static {
89 /// Gets the `TypeId` of `self`.
94 /// use std::any::{Any, TypeId};
96 /// fn is_string(s: &dyn Any) -> bool {
97 /// TypeId::of::<String>() == s.type_id()
100 /// assert_eq!(is_string(&0), false);
101 /// assert_eq!(is_string(&"cookie monster".to_string()), true);
103 #[stable(feature = "get_type_id", since = "1.34.0")]
104 fn type_id(&self) -> TypeId;
107 #[stable(feature = "rust1", since = "1.0.0")]
108 impl<T: 'static + ?Sized> Any for T {
109 fn type_id(&self) -> TypeId {
114 ///////////////////////////////////////////////////////////////////////////////
115 // Extension methods for Any trait objects.
116 ///////////////////////////////////////////////////////////////////////////////
118 #[stable(feature = "rust1", since = "1.0.0")]
119 impl fmt::Debug for dyn Any {
120 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
125 // Ensure that the result of e.g., joining a thread can be printed and
126 // hence used with `unwrap`. May eventually no longer be needed if
127 // dispatch works with upcasting.
128 #[stable(feature = "rust1", since = "1.0.0")]
129 impl fmt::Debug for dyn Any + Send {
130 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
135 #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
136 impl fmt::Debug for dyn Any + Send + Sync {
137 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
143 /// Returns `true` if the boxed type is the same as `T`.
148 /// use std::any::Any;
150 /// fn is_string(s: &dyn Any) {
151 /// if s.is::<String>() {
152 /// println!("It's a string!");
154 /// println!("Not a string...");
159 /// is_string(&"cookie monster".to_string());
161 #[stable(feature = "rust1", since = "1.0.0")]
163 pub fn is<T: Any>(&self) -> bool {
164 // Get `TypeId` of the type this function is instantiated with.
165 let t = TypeId::of::<T>();
167 // Get `TypeId` of the type in the trait object (`self`).
168 let concrete = self.type_id();
170 // Compare both `TypeId`s on equality.
174 /// Returns some reference to the boxed value if it is of type `T`, or
175 /// `None` if it isn't.
180 /// use std::any::Any;
182 /// fn print_if_string(s: &dyn Any) {
183 /// if let Some(string) = s.downcast_ref::<String>() {
184 /// println!("It's a string({}): '{}'", string.len(), string);
186 /// println!("Not a string...");
190 /// print_if_string(&0);
191 /// print_if_string(&"cookie monster".to_string());
193 #[stable(feature = "rust1", since = "1.0.0")]
195 pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
197 // SAFETY: just checked whether we are pointing to the correct type, and we can rely on
198 // that check for memory safety because we have implemented Any for all types; no other
199 // impls can exist as they would conflict with our impl.
200 unsafe { Some(&*(self as *const dyn Any as *const T)) }
206 /// Returns some mutable reference to the boxed value if it is of type `T`, or
207 /// `None` if it isn't.
212 /// use std::any::Any;
214 /// fn modify_if_u32(s: &mut dyn Any) {
215 /// if let Some(num) = s.downcast_mut::<u32>() {
220 /// let mut x = 10u32;
221 /// let mut s = "starlord".to_string();
223 /// modify_if_u32(&mut x);
224 /// modify_if_u32(&mut s);
226 /// assert_eq!(x, 42);
227 /// assert_eq!(&s, "starlord");
229 #[stable(feature = "rust1", since = "1.0.0")]
231 pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
233 // SAFETY: just checked whether we are pointing to the correct type, and we can rely on
234 // that check for memory safety because we have implemented Any for all types; no other
235 // impls can exist as they would conflict with our impl.
236 unsafe { Some(&mut *(self as *mut dyn Any as *mut T)) }
243 impl dyn Any + Send {
244 /// Forwards to the method defined on the type `Any`.
249 /// use std::any::Any;
251 /// fn is_string(s: &(dyn Any + Send)) {
252 /// if s.is::<String>() {
253 /// println!("It's a string!");
255 /// println!("Not a string...");
260 /// is_string(&"cookie monster".to_string());
262 #[stable(feature = "rust1", since = "1.0.0")]
264 pub fn is<T: Any>(&self) -> bool {
268 /// Forwards to the method defined on the type `Any`.
273 /// use std::any::Any;
275 /// fn print_if_string(s: &(dyn Any + Send)) {
276 /// if let Some(string) = s.downcast_ref::<String>() {
277 /// println!("It's a string({}): '{}'", string.len(), string);
279 /// println!("Not a string...");
283 /// print_if_string(&0);
284 /// print_if_string(&"cookie monster".to_string());
286 #[stable(feature = "rust1", since = "1.0.0")]
288 pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
289 Any::downcast_ref::<T>(self)
292 /// Forwards to the method defined on the type `Any`.
297 /// use std::any::Any;
299 /// fn modify_if_u32(s: &mut (dyn Any + Send)) {
300 /// if let Some(num) = s.downcast_mut::<u32>() {
305 /// let mut x = 10u32;
306 /// let mut s = "starlord".to_string();
308 /// modify_if_u32(&mut x);
309 /// modify_if_u32(&mut s);
311 /// assert_eq!(x, 42);
312 /// assert_eq!(&s, "starlord");
314 #[stable(feature = "rust1", since = "1.0.0")]
316 pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
317 Any::downcast_mut::<T>(self)
321 impl dyn Any + Send + Sync {
322 /// Forwards to the method defined on the type `Any`.
327 /// use std::any::Any;
329 /// fn is_string(s: &(dyn Any + Send + Sync)) {
330 /// if s.is::<String>() {
331 /// println!("It's a string!");
333 /// println!("Not a string...");
338 /// is_string(&"cookie monster".to_string());
340 #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
342 pub fn is<T: Any>(&self) -> bool {
346 /// Forwards to the method defined on the type `Any`.
351 /// use std::any::Any;
353 /// fn print_if_string(s: &(dyn Any + Send + Sync)) {
354 /// if let Some(string) = s.downcast_ref::<String>() {
355 /// println!("It's a string({}): '{}'", string.len(), string);
357 /// println!("Not a string...");
361 /// print_if_string(&0);
362 /// print_if_string(&"cookie monster".to_string());
364 #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
366 pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
367 Any::downcast_ref::<T>(self)
370 /// Forwards to the method defined on the type `Any`.
375 /// use std::any::Any;
377 /// fn modify_if_u32(s: &mut (dyn Any + Send + Sync)) {
378 /// if let Some(num) = s.downcast_mut::<u32>() {
383 /// let mut x = 10u32;
384 /// let mut s = "starlord".to_string();
386 /// modify_if_u32(&mut x);
387 /// modify_if_u32(&mut s);
389 /// assert_eq!(x, 42);
390 /// assert_eq!(&s, "starlord");
392 #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
394 pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
395 Any::downcast_mut::<T>(self)
399 ///////////////////////////////////////////////////////////////////////////////
400 // TypeID and its methods
401 ///////////////////////////////////////////////////////////////////////////////
403 /// A `TypeId` represents a globally unique identifier for a type.
405 /// Each `TypeId` is an opaque object which does not allow inspection of what's
406 /// inside but does allow basic operations such as cloning, comparison,
407 /// printing, and showing.
409 /// A `TypeId` is currently only available for types which ascribe to `'static`,
410 /// but this limitation may be removed in the future.
412 /// While `TypeId` implements `Hash`, `PartialOrd`, and `Ord`, it is worth
413 /// noting that the hashes and ordering will vary between Rust releases. Beware
414 /// of relying on them inside of your code!
415 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
416 #[stable(feature = "rust1", since = "1.0.0")]
422 /// Returns the `TypeId` of the type this generic function has been
423 /// instantiated with.
428 /// use std::any::{Any, TypeId};
430 /// fn is_string<T: ?Sized + Any>(_s: &T) -> bool {
431 /// TypeId::of::<String>() == TypeId::of::<T>()
434 /// assert_eq!(is_string(&0), false);
435 /// assert_eq!(is_string(&"cookie monster".to_string()), true);
437 #[stable(feature = "rust1", since = "1.0.0")]
438 #[rustc_const_unstable(feature = "const_type_id", issue = "41875")]
439 pub const fn of<T: ?Sized + 'static>() -> TypeId {
440 TypeId { t: intrinsics::type_id::<T>() }
444 /// Returns the name of a type as a string slice.
448 /// This is intended for diagnostic use. The exact contents and format of the
449 /// string returned are not specified, other than being a best-effort
450 /// description of the type. For example, amongst the strings
451 /// that `type_name::<Option<String>>()` might return are `"Option<String>"` and
452 /// `"std::option::Option<std::string::String>"`.
454 /// The returned string must not be considered to be a unique identifier of a
455 /// type as multiple types may map to the same type name. Similarly, there is no
456 /// guarantee that all parts of a type will appear in the returned string: for
457 /// example, lifetime specifiers are currently not included. In addition, the
458 /// output may change between versions of the compiler.
460 /// The current implementation uses the same infrastructure as compiler
461 /// diagnostics and debuginfo, but this is not guaranteed.
467 /// std::any::type_name::<Option<String>>(),
468 /// "core::option::Option<alloc::string::String>",
471 #[stable(feature = "type_name", since = "1.38.0")]
472 #[rustc_const_unstable(feature = "const_type_name", issue = "63084")]
473 pub const fn type_name<T: ?Sized>() -> &'static str {
474 intrinsics::type_name::<T>()
477 /// Returns the name of the type of the pointed-to value as a string slice.
478 /// This is the same as `type_name::<T>()`, but can be used where the type of a
479 /// variable is not easily available.
483 /// This is intended for diagnostic use. The exact contents and format of the
484 /// string are not specified, other than being a best-effort description of the
485 /// type. For example, `type_name_of_val::<Option<String>>(None)` could return
486 /// `"Option<String>"` or `"std::option::Option<std::string::String>"`, but not
487 /// `"foobar"`. In addition, the output may change between versions of the
490 /// This function does not resolve trait objects,
491 /// meaning that `type_name_of_val(&7u32 as &dyn Debug)`
492 /// may return `"dyn Debug"`, but not `"u32"`.
494 /// The type name should not be considered a unique identifier of a type;
495 /// multiple types may share the same type name.
497 /// The current implementation uses the same infrastructure as compiler
498 /// diagnostics and debuginfo, but this is not guaranteed.
502 /// Prints the default integer and float types.
505 /// #![feature(type_name_of_val)]
506 /// use std::any::type_name_of_val;
509 /// println!("{}", type_name_of_val(&x));
511 /// println!("{}", type_name_of_val(&y));
513 #[unstable(feature = "type_name_of_val", issue = "66359")]
514 #[rustc_const_unstable(feature = "const_type_name", issue = "63084")]
515 pub const fn type_name_of_val<T: ?Sized>(_val: &T) -> &'static str {