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 pub trait Any
: '
static {
112 /// Gets the `TypeId` of `self`.
117 /// use std::any::{Any, TypeId};
119 /// fn is_string(s: &dyn Any) -> bool {
120 /// TypeId::of::<String>() == s.type_id()
123 /// assert_eq!(is_string(&0), false);
124 /// assert_eq!(is_string(&"cookie monster".to_string()), true);
126 #[stable(feature = "get_type_id", since = "1.34.0")]
127 fn type_id(&self) -> TypeId
;
130 #[stable(feature = "rust1", since = "1.0.0")]
131 impl<T
: '
static + ?Sized
> Any
for T
{
132 fn type_id(&self) -> TypeId
{
137 ///////////////////////////////////////////////////////////////////////////////
138 // Extension methods for Any trait objects.
139 ///////////////////////////////////////////////////////////////////////////////
141 #[stable(feature = "rust1", since = "1.0.0")]
142 impl fmt
::Debug
for dyn Any
{
143 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
148 // Ensure that the result of e.g., joining a thread can be printed and
149 // hence used with `unwrap`. May eventually no longer be needed if
150 // dispatch works with upcasting.
151 #[stable(feature = "rust1", since = "1.0.0")]
152 impl fmt
::Debug
for dyn Any
+ Send
{
153 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
158 #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
159 impl fmt
::Debug
for dyn Any
+ Send
+ Sync
{
160 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
166 /// Returns `true` if the boxed type is the same as `T`.
171 /// use std::any::Any;
173 /// fn is_string(s: &dyn Any) {
174 /// if s.is::<String>() {
175 /// println!("It's a string!");
177 /// println!("Not a string...");
182 /// is_string(&"cookie monster".to_string());
184 #[stable(feature = "rust1", since = "1.0.0")]
186 pub fn is
<T
: Any
>(&self) -> bool
{
187 // Get `TypeId` of the type this function is instantiated with.
188 let t
= TypeId
::of
::<T
>();
190 // Get `TypeId` of the type in the trait object (`self`).
191 let concrete
= self.type_id();
193 // Compare both `TypeId`s on equality.
197 /// Returns some reference to the boxed value if it is of type `T`, or
198 /// `None` if it isn't.
203 /// use std::any::Any;
205 /// fn print_if_string(s: &dyn Any) {
206 /// if let Some(string) = s.downcast_ref::<String>() {
207 /// println!("It's a string({}): '{}'", string.len(), string);
209 /// println!("Not a string...");
213 /// print_if_string(&0);
214 /// print_if_string(&"cookie monster".to_string());
216 #[stable(feature = "rust1", since = "1.0.0")]
218 pub fn downcast_ref
<T
: Any
>(&self) -> Option
<&T
> {
220 // SAFETY: just checked whether we are pointing to the correct type, and we can rely on
221 // that check for memory safety because we have implemented Any for all types; no other
222 // impls can exist as they would conflict with our impl.
223 unsafe { Some(&*(self as *const dyn Any as *const T)) }
229 /// Returns some mutable reference to the boxed value if it is of type `T`, or
230 /// `None` if it isn't.
235 /// use std::any::Any;
237 /// fn modify_if_u32(s: &mut dyn Any) {
238 /// if let Some(num) = s.downcast_mut::<u32>() {
243 /// let mut x = 10u32;
244 /// let mut s = "starlord".to_string();
246 /// modify_if_u32(&mut x);
247 /// modify_if_u32(&mut s);
249 /// assert_eq!(x, 42);
250 /// assert_eq!(&s, "starlord");
252 #[stable(feature = "rust1", since = "1.0.0")]
254 pub fn downcast_mut
<T
: Any
>(&mut self) -> Option
<&mut T
> {
256 // SAFETY: just checked whether we are pointing to the correct type, and we can rely on
257 // that check for memory safety because we have implemented Any for all types; no other
258 // impls can exist as they would conflict with our impl.
259 unsafe { Some(&mut *(self as *mut dyn Any as *mut T)) }
266 impl dyn Any
+ Send
{
267 /// Forwards to the method defined on the type `Any`.
272 /// use std::any::Any;
274 /// fn is_string(s: &(dyn Any + Send)) {
275 /// if s.is::<String>() {
276 /// println!("It's a string!");
278 /// println!("Not a string...");
283 /// is_string(&"cookie monster".to_string());
285 #[stable(feature = "rust1", since = "1.0.0")]
287 pub fn is
<T
: Any
>(&self) -> bool
{
288 <dyn Any
>::is
::<T
>(self)
291 /// Forwards to the method defined on the type `Any`.
296 /// use std::any::Any;
298 /// fn print_if_string(s: &(dyn Any + Send)) {
299 /// if let Some(string) = s.downcast_ref::<String>() {
300 /// println!("It's a string({}): '{}'", string.len(), string);
302 /// println!("Not a string...");
306 /// print_if_string(&0);
307 /// print_if_string(&"cookie monster".to_string());
309 #[stable(feature = "rust1", since = "1.0.0")]
311 pub fn downcast_ref
<T
: Any
>(&self) -> Option
<&T
> {
312 <dyn Any
>::downcast_ref
::<T
>(self)
315 /// Forwards to the method defined on the type `Any`.
320 /// use std::any::Any;
322 /// fn modify_if_u32(s: &mut (dyn Any + Send)) {
323 /// if let Some(num) = s.downcast_mut::<u32>() {
328 /// let mut x = 10u32;
329 /// let mut s = "starlord".to_string();
331 /// modify_if_u32(&mut x);
332 /// modify_if_u32(&mut s);
334 /// assert_eq!(x, 42);
335 /// assert_eq!(&s, "starlord");
337 #[stable(feature = "rust1", since = "1.0.0")]
339 pub fn downcast_mut
<T
: Any
>(&mut self) -> Option
<&mut T
> {
340 <dyn Any
>::downcast_mut
::<T
>(self)
344 impl dyn Any
+ Send
+ Sync
{
345 /// Forwards to the method defined on the type `Any`.
350 /// use std::any::Any;
352 /// fn is_string(s: &(dyn Any + Send + Sync)) {
353 /// if s.is::<String>() {
354 /// println!("It's a string!");
356 /// println!("Not a string...");
361 /// is_string(&"cookie monster".to_string());
363 #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
365 pub fn is
<T
: Any
>(&self) -> bool
{
366 <dyn Any
>::is
::<T
>(self)
369 /// Forwards to the method defined on the type `Any`.
374 /// use std::any::Any;
376 /// fn print_if_string(s: &(dyn Any + Send + Sync)) {
377 /// if let Some(string) = s.downcast_ref::<String>() {
378 /// println!("It's a string({}): '{}'", string.len(), string);
380 /// println!("Not a string...");
384 /// print_if_string(&0);
385 /// print_if_string(&"cookie monster".to_string());
387 #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
389 pub fn downcast_ref
<T
: Any
>(&self) -> Option
<&T
> {
390 <dyn Any
>::downcast_ref
::<T
>(self)
393 /// Forwards to the method defined on the type `Any`.
398 /// use std::any::Any;
400 /// fn modify_if_u32(s: &mut (dyn Any + Send + Sync)) {
401 /// if let Some(num) = s.downcast_mut::<u32>() {
406 /// let mut x = 10u32;
407 /// let mut s = "starlord".to_string();
409 /// modify_if_u32(&mut x);
410 /// modify_if_u32(&mut s);
412 /// assert_eq!(x, 42);
413 /// assert_eq!(&s, "starlord");
415 #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
417 pub fn downcast_mut
<T
: Any
>(&mut self) -> Option
<&mut T
> {
418 <dyn Any
>::downcast_mut
::<T
>(self)
422 ///////////////////////////////////////////////////////////////////////////////
423 // TypeID and its methods
424 ///////////////////////////////////////////////////////////////////////////////
426 /// A `TypeId` represents a globally unique identifier for a type.
428 /// Each `TypeId` is an opaque object which does not allow inspection of what's
429 /// inside but does allow basic operations such as cloning, comparison,
430 /// printing, and showing.
432 /// A `TypeId` is currently only available for types which ascribe to `'static`,
433 /// but this limitation may be removed in the future.
435 /// While `TypeId` implements `Hash`, `PartialOrd`, and `Ord`, it is worth
436 /// noting that the hashes and ordering will vary between Rust releases. Beware
437 /// of relying on them inside of your code!
438 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
439 #[stable(feature = "rust1", since = "1.0.0")]
445 /// Returns the `TypeId` of the type this generic function has been
446 /// instantiated with.
451 /// use std::any::{Any, TypeId};
453 /// fn is_string<T: ?Sized + Any>(_s: &T) -> bool {
454 /// TypeId::of::<String>() == TypeId::of::<T>()
457 /// assert_eq!(is_string(&0), false);
458 /// assert_eq!(is_string(&"cookie monster".to_string()), true);
460 #[stable(feature = "rust1", since = "1.0.0")]
461 #[rustc_const_unstable(feature = "const_type_id", issue = "77125")]
462 pub const fn of
<T
: ?Sized
+ '
static>() -> TypeId
{
463 TypeId { t: intrinsics::type_id::<T>() }
467 /// Returns the name of a type as a string slice.
471 /// This is intended for diagnostic use. The exact contents and format of the
472 /// string returned are not specified, other than being a best-effort
473 /// description of the type. For example, amongst the strings
474 /// that `type_name::<Option<String>>()` might return are `"Option<String>"` and
475 /// `"std::option::Option<std::string::String>"`.
477 /// The returned string must not be considered to be a unique identifier of a
478 /// type as multiple types may map to the same type name. Similarly, there is no
479 /// guarantee that all parts of a type will appear in the returned string: for
480 /// example, lifetime specifiers are currently not included. In addition, the
481 /// output may change between versions of the compiler.
483 /// The current implementation uses the same infrastructure as compiler
484 /// diagnostics and debuginfo, but this is not guaranteed.
490 /// std::any::type_name::<Option<String>>(),
491 /// "core::option::Option<alloc::string::String>",
494 #[stable(feature = "type_name", since = "1.38.0")]
495 #[rustc_const_unstable(feature = "const_type_name", issue = "63084")]
496 pub const fn type_name
<T
: ?Sized
>() -> &'
static str {
497 intrinsics
::type_name
::<T
>()
500 /// Returns the name of the type of the pointed-to value as a string slice.
501 /// This is the same as `type_name::<T>()`, but can be used where the type of a
502 /// variable is not easily available.
506 /// This is intended for diagnostic use. The exact contents and format of the
507 /// string are not specified, other than being a best-effort description of the
508 /// type. For example, `type_name_of_val::<Option<String>>(None)` could return
509 /// `"Option<String>"` or `"std::option::Option<std::string::String>"`, but not
510 /// `"foobar"`. In addition, the output may change between versions of the
513 /// This function does not resolve trait objects,
514 /// meaning that `type_name_of_val(&7u32 as &dyn Debug)`
515 /// may return `"dyn Debug"`, but not `"u32"`.
517 /// The type name should not be considered a unique identifier of a type;
518 /// multiple types may share the same type name.
520 /// The current implementation uses the same infrastructure as compiler
521 /// diagnostics and debuginfo, but this is not guaranteed.
525 /// Prints the default integer and float types.
528 /// #![feature(type_name_of_val)]
529 /// use std::any::type_name_of_val;
532 /// println!("{}", type_name_of_val(&x));
534 /// println!("{}", type_name_of_val(&y));
536 #[unstable(feature = "type_name_of_val", issue = "66359")]
537 #[rustc_const_unstable(feature = "const_type_name", issue = "63084")]
538 pub const fn type_name_of_val
<T
: ?Sized
>(_val
: &T
) -> &'
static str {