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 `&Any` (a borrowed trait object), it has the `is` and
6 //! `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 Any`, there
8 //! is also the `downcast_mut` method, for getting a mutable reference to the
9 //! inner value. `Box<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 &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 type 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()
91 /// assert_eq!(is_string(&0), false);
92 /// assert_eq!(is_string(&"cookie monster".to_string()), true);
95 #[stable(feature = "get_type_id", since = "1.34.0")]
96 fn type_id(&self) -> TypeId;
99 #[stable(feature = "rust1", since = "1.0.0")]
100 impl<T: 'static + ?Sized > Any for T {
101 fn type_id(&self) -> TypeId { TypeId::of::<T>() }
104 ///////////////////////////////////////////////////////////////////////////////
105 // Extension methods for Any trait objects.
106 ///////////////////////////////////////////////////////////////////////////////
108 #[stable(feature = "rust1", since = "1.0.0")]
109 impl fmt::Debug for dyn Any {
110 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
115 // Ensure that the result of e.g., joining a thread can be printed and
116 // hence used with `unwrap`. May eventually no longer be needed if
117 // dispatch works with upcasting.
118 #[stable(feature = "rust1", since = "1.0.0")]
119 impl fmt::Debug for dyn Any + Send {
120 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
125 #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
126 impl fmt::Debug for dyn Any + Send + Sync {
127 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
133 /// Returns `true` if the boxed type is the same as `T`.
138 /// use std::any::Any;
140 /// fn is_string(s: &dyn Any) {
141 /// if s.is::<String>() {
142 /// println!("It's a string!");
144 /// println!("Not a string...");
150 /// is_string(&"cookie monster".to_string());
153 #[stable(feature = "rust1", since = "1.0.0")]
155 pub fn is<T: Any>(&self) -> bool {
156 // Get TypeId of the type this function is instantiated with
157 let t = TypeId::of::<T>();
159 // Get TypeId of the type in the trait object
160 let concrete = self.type_id();
162 // Compare both TypeIds on equality
166 /// Returns some reference to the boxed value if it is of type `T`, or
167 /// `None` if it isn't.
172 /// use std::any::Any;
174 /// fn print_if_string(s: &dyn Any) {
175 /// if let Some(string) = s.downcast_ref::<String>() {
176 /// println!("It's a string({}): '{}'", string.len(), string);
178 /// println!("Not a string...");
183 /// print_if_string(&0);
184 /// print_if_string(&"cookie monster".to_string());
187 #[stable(feature = "rust1", since = "1.0.0")]
189 pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
192 Some(&*(self as *const dyn Any as *const T))
199 /// Returns some mutable reference to the boxed value if it is of type `T`, or
200 /// `None` if it isn't.
205 /// use std::any::Any;
207 /// fn modify_if_u32(s: &mut dyn Any) {
208 /// if let Some(num) = s.downcast_mut::<u32>() {
214 /// let mut x = 10u32;
215 /// let mut s = "starlord".to_string();
217 /// modify_if_u32(&mut x);
218 /// modify_if_u32(&mut s);
220 /// assert_eq!(x, 42);
221 /// assert_eq!(&s, "starlord");
224 #[stable(feature = "rust1", since = "1.0.0")]
226 pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
229 Some(&mut *(self as *mut dyn Any as *mut T))
238 /// Forwards to the method defined on the type `Any`.
243 /// use std::any::Any;
245 /// fn is_string(s: &(dyn Any + Send)) {
246 /// if s.is::<String>() {
247 /// println!("It's a string!");
249 /// println!("Not a string...");
255 /// is_string(&"cookie monster".to_string());
258 #[stable(feature = "rust1", since = "1.0.0")]
260 pub fn is<T: Any>(&self) -> bool {
264 /// Forwards to the method defined on the type `Any`.
269 /// use std::any::Any;
271 /// fn print_if_string(s: &(dyn Any + Send)) {
272 /// if let Some(string) = s.downcast_ref::<String>() {
273 /// println!("It's a string({}): '{}'", string.len(), string);
275 /// println!("Not a string...");
280 /// print_if_string(&0);
281 /// print_if_string(&"cookie monster".to_string());
284 #[stable(feature = "rust1", since = "1.0.0")]
286 pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
287 Any::downcast_ref::<T>(self)
290 /// Forwards to the method defined on the type `Any`.
295 /// use std::any::Any;
297 /// fn modify_if_u32(s: &mut (dyn Any + Send)) {
298 /// if let Some(num) = s.downcast_mut::<u32>() {
304 /// let mut x = 10u32;
305 /// let mut s = "starlord".to_string();
307 /// modify_if_u32(&mut x);
308 /// modify_if_u32(&mut s);
310 /// assert_eq!(x, 42);
311 /// 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...");
339 /// is_string(&"cookie monster".to_string());
342 #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
344 pub fn is<T: Any>(&self) -> bool {
348 /// Forwards to the method defined on the type `Any`.
353 /// use std::any::Any;
355 /// fn print_if_string(s: &(dyn Any + Send + Sync)) {
356 /// if let Some(string) = s.downcast_ref::<String>() {
357 /// println!("It's a string({}): '{}'", string.len(), string);
359 /// println!("Not a string...");
364 /// print_if_string(&0);
365 /// print_if_string(&"cookie monster".to_string());
368 #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
370 pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
371 Any::downcast_ref::<T>(self)
374 /// Forwards to the method defined on the type `Any`.
379 /// use std::any::Any;
381 /// fn modify_if_u32(s: &mut (dyn Any + Send + Sync)) {
382 /// if let Some(num) = s.downcast_mut::<u32>() {
388 /// let mut x = 10u32;
389 /// let mut s = "starlord".to_string();
391 /// modify_if_u32(&mut x);
392 /// modify_if_u32(&mut s);
394 /// assert_eq!(x, 42);
395 /// assert_eq!(&s, "starlord");
398 #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
400 pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
401 Any::downcast_mut::<T>(self)
405 ///////////////////////////////////////////////////////////////////////////////
406 // TypeID and its methods
407 ///////////////////////////////////////////////////////////////////////////////
409 /// A `TypeId` represents a globally unique identifier for a type.
411 /// Each `TypeId` is an opaque object which does not allow inspection of what's
412 /// inside but does allow basic operations such as cloning, comparison,
413 /// printing, and showing.
415 /// A `TypeId` is currently only available for types which ascribe to `'static`,
416 /// but this limitation may be removed in the future.
418 /// While `TypeId` implements `Hash`, `PartialOrd`, and `Ord`, it is worth
419 /// noting that the hashes and ordering will vary between Rust releases. Beware
420 /// of relying on them inside of your code!
421 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
422 #[stable(feature = "rust1", since = "1.0.0")]
428 /// Returns the `TypeId` of the type this generic function has been
429 /// instantiated with.
434 /// use std::any::{Any, TypeId};
436 /// fn is_string<T: ?Sized + Any>(_s: &T) -> bool {
437 /// TypeId::of::<String>() == TypeId::of::<T>()
441 /// assert_eq!(is_string(&0), false);
442 /// assert_eq!(is_string(&"cookie monster".to_string()), true);
445 #[stable(feature = "rust1", since = "1.0.0")]
446 #[rustc_const_unstable(feature="const_type_id")]
447 pub const fn of<T: ?Sized + 'static>() -> TypeId {
449 t: unsafe { intrinsics::type_id::<T>() },
454 /// Returns the name of a type as a string slice.
458 /// This is intended for diagnostic use. The exact contents and format of the
459 /// string are not specified, other than being a best-effort description of the
460 /// type. For example, `type_name::<Option<String>>()` could return the
461 /// `"Option<String>"` or `"std::option::Option<std::string::String>"`, but not
462 /// `"foobar"`. In addition, the output may change between versions of the
465 /// The type name should not be considered a unique identifier of a type;
466 /// multiple types may share the same type name.
468 /// The current implementation uses the same infrastructure as compiler
469 /// diagnostics and debuginfo, but this is not guaranteed.
470 #[stable(feature = "type_name", since = "1.38.0")]
471 pub fn type_name<T: ?Sized>() -> &'static str {
474 intrinsics::type_name::<T>()
476 #[cfg(not(bootstrap))]
477 intrinsics::type_name::<T>()