2013-10-11 21:20:34 +00:00
|
|
|
//! This module implements the `Any` trait, which enables dynamic typing
|
2014-06-12 07:54:03 +00:00
|
|
|
//! of any `'static` type through runtime reflection.
|
2013-12-06 17:33:08 +00:00
|
|
|
//!
|
2014-07-06 16:30:01 +00:00
|
|
|
//! `Any` itself can be used to get a `TypeId`, and has more features when used
|
2019-10-13 11:48:07 +00:00
|
|
|
//! as a trait object. As `&dyn Any` (a borrowed trait object), it has the `is`
|
|
|
|
//! and `downcast_ref` methods, to test if the contained value is of a given type,
|
|
|
|
//! and to get a reference to the inner value as a type. As `&mut dyn Any`, there
|
2015-08-26 17:59:39 +00:00
|
|
|
//! is also the `downcast_mut` method, for getting a mutable reference to the
|
2019-10-13 11:48:07 +00:00
|
|
|
//! inner value. `Box<dyn Any>` adds the `downcast` method, which attempts to
|
2015-12-11 23:44:11 +00:00
|
|
|
//! convert to a `Box<T>`. See the [`Box`] documentation for the full details.
|
2014-07-06 16:30:01 +00:00
|
|
|
//!
|
2019-10-13 12:03:21 +00:00
|
|
|
//! Note that `&dyn Any` is limited to testing whether a value is of a specified
|
2014-07-06 16:30:01 +00:00
|
|
|
//! concrete type, and cannot be used to test whether a type implements a trait.
|
|
|
|
//!
|
2016-03-08 07:55:52 +00:00
|
|
|
//! [`Box`]: ../../std/boxed/struct.Box.html
|
2015-12-11 23:44:11 +00:00
|
|
|
//!
|
2014-07-06 16:30:01 +00:00
|
|
|
//! # Examples
|
|
|
|
//!
|
|
|
|
//! Consider a situation where we want to log out a value passed to a function.
|
2015-02-05 12:04:07 +00:00
|
|
|
//! We know the value we're working on implements Debug, but we don't know its
|
2019-02-09 21:23:30 +00:00
|
|
|
//! concrete type. We want to give special treatment to certain types: in this
|
2014-07-06 16:30:01 +00:00
|
|
|
//! case printing out the length of String values prior to their value.
|
|
|
|
//! We don't know the concrete type of our value at compile time, so we need to
|
|
|
|
//! use runtime reflection instead.
|
|
|
|
//!
|
|
|
|
//! ```rust
|
2015-01-20 23:45:07 +00:00
|
|
|
//! use std::fmt::Debug;
|
2015-01-01 06:13:08 +00:00
|
|
|
//! use std::any::Any;
|
2014-07-06 16:30:01 +00:00
|
|
|
//!
|
2015-01-20 23:45:07 +00:00
|
|
|
//! // Logger function for any type that implements Debug.
|
|
|
|
//! fn log<T: Any + Debug>(value: &T) {
|
2018-11-19 06:59:21 +00:00
|
|
|
//! let value_any = value as &dyn Any;
|
2014-07-06 16:30:01 +00:00
|
|
|
//!
|
2019-02-09 21:23:30 +00:00
|
|
|
//! // Try to convert our value to a `String`. If successful, we want to
|
|
|
|
//! // output the String`'s length as well as its value. If not, it's a
|
2014-07-06 16:30:01 +00:00
|
|
|
//! // different type: just print it out unadorned.
|
std: Stabilize unit, bool, ty, tuple, arc, any
This commit applies stability attributes to the contents of these modules,
summarized here:
* The `unit` and `bool` modules have become #[unstable] as they are purely meant
for documentation purposes and are candidates for removal.
* The `ty` module has been deprecated, and the inner `Unsafe` type has been
renamed to `UnsafeCell` and moved to the `cell` module. The `marker1` field
has been removed as the compiler now always infers `UnsafeCell` to be
invariant. The `new` method i stable, but the `value` field, `get` and
`unwrap` methods are all unstable.
* The `tuple` module has its name as stable, the naming of the `TupleN` traits
as stable while the methods are all #[unstable]. The other impls in the module
have appropriate stability for the corresponding trait.
* The `arc` module has received the exact same treatment as the `rc` module
previously did.
* The `any` module has its name as stable. The `Any` trait is also stable, with
a new private supertrait which now contains the `get_type_id` method. This is
to make the method a private implementation detail rather than a public-facing
detail.
The two extension traits in the module are marked #[unstable] as they will not
be necessary with DST. The `is` method is #[stable], the as_{mut,ref} methods
have been renamed to downcast_{mut,ref} and are #[unstable].
The extension trait `BoxAny` has been clarified as to why it is unstable as it
will not be necessary with DST.
This is a breaking change because the `marker1` field was removed from the
`UnsafeCell` type. To deal with this change, you can simply delete the field and
only specify the value of the `data` field in static initializers.
[breaking-change]
2014-07-24 02:10:12 +00:00
|
|
|
//! match value_any.downcast_ref::<String>() {
|
2014-07-06 16:30:01 +00:00
|
|
|
//! Some(as_string) => {
|
2015-01-07 00:16:35 +00:00
|
|
|
//! println!("String ({}): {}", as_string.len(), as_string);
|
2014-07-06 16:30:01 +00:00
|
|
|
//! }
|
|
|
|
//! None => {
|
2015-01-07 00:16:35 +00:00
|
|
|
//! println!("{:?}", value);
|
2014-07-06 16:30:01 +00:00
|
|
|
//! }
|
|
|
|
//! }
|
|
|
|
//! }
|
|
|
|
//!
|
|
|
|
//! // This function wants to log its parameter out prior to doing work with it.
|
2015-03-24 19:55:29 +00:00
|
|
|
//! fn do_work<T: Any + Debug>(value: &T) {
|
2014-07-06 16:30:01 +00:00
|
|
|
//! log(value);
|
|
|
|
//! // ...do some other work
|
|
|
|
//! }
|
|
|
|
//!
|
|
|
|
//! fn main() {
|
|
|
|
//! let my_string = "Hello World".to_string();
|
|
|
|
//! do_work(&my_string);
|
|
|
|
//!
|
|
|
|
//! let my_i8: i8 = 100;
|
|
|
|
//! do_work(&my_i8);
|
|
|
|
//! }
|
|
|
|
//! ```
|
2013-10-11 21:20:34 +00:00
|
|
|
|
2015-01-24 05:48:20 +00:00
|
|
|
#![stable(feature = "rust1", since = "1.0.0")]
|
std: Stabilize unit, bool, ty, tuple, arc, any
This commit applies stability attributes to the contents of these modules,
summarized here:
* The `unit` and `bool` modules have become #[unstable] as they are purely meant
for documentation purposes and are candidates for removal.
* The `ty` module has been deprecated, and the inner `Unsafe` type has been
renamed to `UnsafeCell` and moved to the `cell` module. The `marker1` field
has been removed as the compiler now always infers `UnsafeCell` to be
invariant. The `new` method i stable, but the `value` field, `get` and
`unwrap` methods are all unstable.
* The `tuple` module has its name as stable, the naming of the `TupleN` traits
as stable while the methods are all #[unstable]. The other impls in the module
have appropriate stability for the corresponding trait.
* The `arc` module has received the exact same treatment as the `rc` module
previously did.
* The `any` module has its name as stable. The `Any` trait is also stable, with
a new private supertrait which now contains the `get_type_id` method. This is
to make the method a private implementation detail rather than a public-facing
detail.
The two extension traits in the module are marked #[unstable] as they will not
be necessary with DST. The `is` method is #[stable], the as_{mut,ref} methods
have been renamed to downcast_{mut,ref} and are #[unstable].
The extension trait `BoxAny` has been clarified as to why it is unstable as it
will not be necessary with DST.
This is a breaking change because the `marker1` field was removed from the
`UnsafeCell` type. To deal with this change, you can simply delete the field and
only specify the value of the `data` field in static initializers.
[breaking-change]
2014-07-24 02:10:12 +00:00
|
|
|
|
2019-04-15 02:23:21 +00:00
|
|
|
use crate::fmt;
|
|
|
|
use crate::intrinsics;
|
2014-01-31 20:35:36 +00:00
|
|
|
|
2013-10-11 21:20:34 +00:00
|
|
|
///////////////////////////////////////////////////////////////////////////////
|
|
|
|
// Any trait
|
|
|
|
///////////////////////////////////////////////////////////////////////////////
|
|
|
|
|
2019-11-29 18:47:16 +00:00
|
|
|
/// A trait to emulate dynamic typing.
|
2014-06-12 07:54:03 +00:00
|
|
|
///
|
2016-06-07 17:19:08 +00:00
|
|
|
/// Most types implement `Any`. However, any type which contains a non-`'static` reference does not.
|
2015-04-06 15:36:37 +00:00
|
|
|
/// See the [module-level documentation][mod] for more details.
|
2015-03-24 16:15:49 +00:00
|
|
|
///
|
2015-04-06 15:36:37 +00:00
|
|
|
/// [mod]: index.html
|
2015-01-24 05:48:20 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2016-10-06 05:28:27 +00:00
|
|
|
pub trait Any: 'static {
|
2015-04-13 14:21:32 +00:00
|
|
|
/// Gets the `TypeId` of `self`.
|
2016-07-10 13:09:55 +00:00
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// use std::any::{Any, TypeId};
|
|
|
|
///
|
2018-11-19 06:59:21 +00:00
|
|
|
/// fn is_string(s: &dyn Any) -> bool {
|
2019-01-22 13:25:27 +00:00
|
|
|
/// TypeId::of::<String>() == s.type_id()
|
2016-07-10 13:09:55 +00:00
|
|
|
/// }
|
|
|
|
///
|
2019-10-01 11:55:46 +00:00
|
|
|
/// assert_eq!(is_string(&0), false);
|
|
|
|
/// assert_eq!(is_string(&"cookie monster".to_string()), true);
|
2016-07-10 13:09:55 +00:00
|
|
|
/// ```
|
2019-01-22 13:25:27 +00:00
|
|
|
#[stable(feature = "get_type_id", since = "1.34.0")]
|
|
|
|
fn type_id(&self) -> TypeId;
|
2013-10-30 23:32:33 +00:00
|
|
|
}
|
|
|
|
|
2015-11-16 16:54:28 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2016-10-06 05:28:27 +00:00
|
|
|
impl<T: 'static + ?Sized > Any for T {
|
2019-01-22 13:25:27 +00:00
|
|
|
fn type_id(&self) -> TypeId { TypeId::of::<T>() }
|
2013-10-11 21:20:34 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
///////////////////////////////////////////////////////////////////////////////
|
|
|
|
// Extension methods for Any trait objects.
|
|
|
|
///////////////////////////////////////////////////////////////////////////////
|
|
|
|
|
2015-03-30 21:50:31 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2018-07-10 18:39:28 +00:00
|
|
|
impl fmt::Debug for dyn Any {
|
2019-04-18 23:37:12 +00:00
|
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
2015-03-30 21:50:31 +00:00
|
|
|
f.pad("Any")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-11-27 02:59:49 +00:00
|
|
|
// Ensure that the result of e.g., joining a thread can be printed and
|
2015-04-10 00:23:49 +00:00
|
|
|
// hence used with `unwrap`. May eventually no longer be needed if
|
|
|
|
// dispatch works with upcasting.
|
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2018-07-10 18:39:28 +00:00
|
|
|
impl fmt::Debug for dyn Any + Send {
|
2019-04-18 23:37:12 +00:00
|
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
2015-04-10 00:23:49 +00:00
|
|
|
f.pad("Any")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-05-17 06:09:58 +00:00
|
|
|
#[stable(feature = "any_send_sync_methods", since = "1.28.0")]
|
2018-07-10 18:39:28 +00:00
|
|
|
impl fmt::Debug for dyn Any + Send + Sync {
|
2019-04-18 23:37:12 +00:00
|
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
2018-05-17 06:09:58 +00:00
|
|
|
f.pad("Any")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-07-10 18:39:28 +00:00
|
|
|
impl dyn Any {
|
2017-03-22 00:42:23 +00:00
|
|
|
/// Returns `true` if the boxed type is the same as `T`.
|
2016-07-10 13:09:55 +00:00
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// use std::any::Any;
|
|
|
|
///
|
2018-11-19 06:59:21 +00:00
|
|
|
/// fn is_string(s: &dyn Any) {
|
2016-07-10 13:09:55 +00:00
|
|
|
/// if s.is::<String>() {
|
|
|
|
/// println!("It's a string!");
|
|
|
|
/// } else {
|
|
|
|
/// println!("Not a string...");
|
|
|
|
/// }
|
|
|
|
/// }
|
|
|
|
///
|
2019-10-01 11:55:46 +00:00
|
|
|
/// is_string(&0);
|
|
|
|
/// is_string(&"cookie monster".to_string());
|
2016-07-10 13:09:55 +00:00
|
|
|
/// ```
|
2015-01-24 05:48:20 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2013-10-11 21:20:34 +00:00
|
|
|
#[inline]
|
2015-03-24 19:55:29 +00:00
|
|
|
pub fn is<T: Any>(&self) -> bool {
|
2019-09-05 16:15:28 +00:00
|
|
|
// Get `TypeId` of the type this function is instantiated with.
|
2013-10-11 21:20:34 +00:00
|
|
|
let t = TypeId::of::<T>();
|
|
|
|
|
2019-09-05 16:15:28 +00:00
|
|
|
// Get `TypeId` of the type in the trait object.
|
2019-01-22 13:25:27 +00:00
|
|
|
let concrete = self.type_id();
|
2013-10-11 21:20:34 +00:00
|
|
|
|
2019-09-05 16:15:28 +00:00
|
|
|
// Compare both `TypeId`s on equality.
|
2019-01-22 13:25:27 +00:00
|
|
|
t == concrete
|
2013-10-11 21:20:34 +00:00
|
|
|
}
|
|
|
|
|
2015-01-01 06:13:08 +00:00
|
|
|
/// Returns some reference to the boxed value if it is of type `T`, or
|
|
|
|
/// `None` if it isn't.
|
2016-07-10 13:09:55 +00:00
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// use std::any::Any;
|
|
|
|
///
|
2018-11-19 06:59:21 +00:00
|
|
|
/// fn print_if_string(s: &dyn Any) {
|
2016-07-10 13:09:55 +00:00
|
|
|
/// if let Some(string) = s.downcast_ref::<String>() {
|
|
|
|
/// println!("It's a string({}): '{}'", string.len(), string);
|
|
|
|
/// } else {
|
|
|
|
/// println!("Not a string...");
|
|
|
|
/// }
|
|
|
|
/// }
|
|
|
|
///
|
2019-10-01 11:55:46 +00:00
|
|
|
/// print_if_string(&0);
|
|
|
|
/// print_if_string(&"cookie monster".to_string());
|
2016-07-10 13:09:55 +00:00
|
|
|
/// ```
|
2015-01-24 05:48:20 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2013-10-11 21:20:34 +00:00
|
|
|
#[inline]
|
2015-03-24 19:55:29 +00:00
|
|
|
pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
|
2013-10-11 21:20:34 +00:00
|
|
|
if self.is::<T>() {
|
2019-08-21 17:56:46 +00:00
|
|
|
// SAFETY: just checked whether we are pointing to the correct type
|
2014-03-03 00:01:13 +00:00
|
|
|
unsafe {
|
2018-07-10 18:39:28 +00:00
|
|
|
Some(&*(self as *const dyn Any as *const T))
|
2014-03-03 00:01:13 +00:00
|
|
|
}
|
2013-10-11 21:20:34 +00:00
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns some mutable reference to the boxed value if it is of type `T`, or
|
|
|
|
/// `None` if it isn't.
|
2016-07-10 13:09:55 +00:00
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// use std::any::Any;
|
|
|
|
///
|
2018-11-19 06:59:21 +00:00
|
|
|
/// fn modify_if_u32(s: &mut dyn Any) {
|
2016-07-10 13:09:55 +00:00
|
|
|
/// if let Some(num) = s.downcast_mut::<u32>() {
|
|
|
|
/// *num = 42;
|
|
|
|
/// }
|
|
|
|
/// }
|
|
|
|
///
|
2019-10-01 11:55:46 +00:00
|
|
|
/// let mut x = 10u32;
|
|
|
|
/// let mut s = "starlord".to_string();
|
2016-07-10 13:09:55 +00:00
|
|
|
///
|
2019-10-01 11:55:46 +00:00
|
|
|
/// modify_if_u32(&mut x);
|
|
|
|
/// modify_if_u32(&mut s);
|
2016-07-10 13:09:55 +00:00
|
|
|
///
|
2019-10-01 11:55:46 +00:00
|
|
|
/// assert_eq!(x, 42);
|
|
|
|
/// assert_eq!(&s, "starlord");
|
2016-07-10 13:09:55 +00:00
|
|
|
/// ```
|
2015-01-24 05:48:20 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2013-10-11 21:20:34 +00:00
|
|
|
#[inline]
|
2015-03-24 19:55:29 +00:00
|
|
|
pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
|
2013-10-11 21:20:34 +00:00
|
|
|
if self.is::<T>() {
|
2019-08-21 17:56:46 +00:00
|
|
|
// SAFETY: just checked whether we are pointing to the correct type
|
2014-03-03 00:01:13 +00:00
|
|
|
unsafe {
|
2018-07-10 18:39:28 +00:00
|
|
|
Some(&mut *(self as *mut dyn Any as *mut T))
|
2014-03-03 00:01:13 +00:00
|
|
|
}
|
2013-10-11 21:20:34 +00:00
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2015-01-15 00:08:07 +00:00
|
|
|
|
2018-07-10 18:39:28 +00:00
|
|
|
impl dyn Any+Send {
|
2015-02-17 10:17:19 +00:00
|
|
|
/// Forwards to the method defined on the type `Any`.
|
2016-07-10 13:09:55 +00:00
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// use std::any::Any;
|
|
|
|
///
|
2018-11-19 06:59:21 +00:00
|
|
|
/// fn is_string(s: &(dyn Any + Send)) {
|
2016-07-10 13:09:55 +00:00
|
|
|
/// if s.is::<String>() {
|
|
|
|
/// println!("It's a string!");
|
|
|
|
/// } else {
|
|
|
|
/// println!("Not a string...");
|
|
|
|
/// }
|
|
|
|
/// }
|
|
|
|
///
|
2019-10-01 11:55:46 +00:00
|
|
|
/// is_string(&0);
|
|
|
|
/// is_string(&"cookie monster".to_string());
|
2016-07-10 13:09:55 +00:00
|
|
|
/// ```
|
2015-02-17 10:17:19 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
|
|
|
#[inline]
|
2015-03-24 19:55:29 +00:00
|
|
|
pub fn is<T: Any>(&self) -> bool {
|
2015-02-17 10:17:19 +00:00
|
|
|
Any::is::<T>(self)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Forwards to the method defined on the type `Any`.
|
2016-07-10 13:09:55 +00:00
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// use std::any::Any;
|
|
|
|
///
|
2018-11-19 06:59:21 +00:00
|
|
|
/// fn print_if_string(s: &(dyn Any + Send)) {
|
2016-07-10 13:09:55 +00:00
|
|
|
/// if let Some(string) = s.downcast_ref::<String>() {
|
|
|
|
/// println!("It's a string({}): '{}'", string.len(), string);
|
|
|
|
/// } else {
|
|
|
|
/// println!("Not a string...");
|
|
|
|
/// }
|
|
|
|
/// }
|
|
|
|
///
|
2019-10-01 11:55:46 +00:00
|
|
|
/// print_if_string(&0);
|
|
|
|
/// print_if_string(&"cookie monster".to_string());
|
2016-07-10 13:09:55 +00:00
|
|
|
/// ```
|
2015-02-17 10:17:19 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
|
|
|
#[inline]
|
2015-03-24 19:55:29 +00:00
|
|
|
pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
|
2015-02-17 10:17:19 +00:00
|
|
|
Any::downcast_ref::<T>(self)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Forwards to the method defined on the type `Any`.
|
2016-07-10 13:09:55 +00:00
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// use std::any::Any;
|
|
|
|
///
|
2018-11-19 06:59:21 +00:00
|
|
|
/// fn modify_if_u32(s: &mut (dyn Any + Send)) {
|
2016-07-10 13:09:55 +00:00
|
|
|
/// if let Some(num) = s.downcast_mut::<u32>() {
|
|
|
|
/// *num = 42;
|
|
|
|
/// }
|
|
|
|
/// }
|
|
|
|
///
|
2019-10-01 11:55:46 +00:00
|
|
|
/// let mut x = 10u32;
|
|
|
|
/// let mut s = "starlord".to_string();
|
2016-07-10 13:09:55 +00:00
|
|
|
///
|
2019-10-01 11:55:46 +00:00
|
|
|
/// modify_if_u32(&mut x);
|
|
|
|
/// modify_if_u32(&mut s);
|
2016-07-10 13:09:55 +00:00
|
|
|
///
|
2019-10-01 11:55:46 +00:00
|
|
|
/// assert_eq!(x, 42);
|
|
|
|
/// assert_eq!(&s, "starlord");
|
2016-07-10 13:09:55 +00:00
|
|
|
/// ```
|
2015-02-17 10:17:19 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
|
|
|
#[inline]
|
2015-03-24 19:55:29 +00:00
|
|
|
pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
|
2015-02-17 10:17:19 +00:00
|
|
|
Any::downcast_mut::<T>(self)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-07-10 18:39:28 +00:00
|
|
|
impl dyn Any+Send+Sync {
|
2018-05-17 06:09:58 +00:00
|
|
|
/// Forwards to the method defined on the type `Any`.
|
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// use std::any::Any;
|
|
|
|
///
|
2018-11-19 06:59:21 +00:00
|
|
|
/// fn is_string(s: &(dyn Any + Send + Sync)) {
|
2018-05-17 06:09:58 +00:00
|
|
|
/// if s.is::<String>() {
|
|
|
|
/// println!("It's a string!");
|
|
|
|
/// } else {
|
|
|
|
/// println!("Not a string...");
|
|
|
|
/// }
|
|
|
|
/// }
|
|
|
|
///
|
2019-10-01 11:55:46 +00:00
|
|
|
/// is_string(&0);
|
|
|
|
/// is_string(&"cookie monster".to_string());
|
2018-05-17 06:09:58 +00:00
|
|
|
/// ```
|
|
|
|
#[stable(feature = "any_send_sync_methods", since = "1.28.0")]
|
|
|
|
#[inline]
|
|
|
|
pub fn is<T: Any>(&self) -> bool {
|
|
|
|
Any::is::<T>(self)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Forwards to the method defined on the type `Any`.
|
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// use std::any::Any;
|
|
|
|
///
|
2018-11-19 06:59:21 +00:00
|
|
|
/// fn print_if_string(s: &(dyn Any + Send + Sync)) {
|
2018-05-17 06:09:58 +00:00
|
|
|
/// if let Some(string) = s.downcast_ref::<String>() {
|
|
|
|
/// println!("It's a string({}): '{}'", string.len(), string);
|
|
|
|
/// } else {
|
|
|
|
/// println!("Not a string...");
|
|
|
|
/// }
|
|
|
|
/// }
|
|
|
|
///
|
2019-10-01 11:55:46 +00:00
|
|
|
/// print_if_string(&0);
|
|
|
|
/// print_if_string(&"cookie monster".to_string());
|
2018-05-17 06:09:58 +00:00
|
|
|
/// ```
|
|
|
|
#[stable(feature = "any_send_sync_methods", since = "1.28.0")]
|
|
|
|
#[inline]
|
|
|
|
pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
|
|
|
|
Any::downcast_ref::<T>(self)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Forwards to the method defined on the type `Any`.
|
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// use std::any::Any;
|
|
|
|
///
|
2018-11-19 06:59:21 +00:00
|
|
|
/// fn modify_if_u32(s: &mut (dyn Any + Send + Sync)) {
|
2018-05-17 06:09:58 +00:00
|
|
|
/// if let Some(num) = s.downcast_mut::<u32>() {
|
|
|
|
/// *num = 42;
|
|
|
|
/// }
|
|
|
|
/// }
|
|
|
|
///
|
2019-10-01 11:55:46 +00:00
|
|
|
/// let mut x = 10u32;
|
|
|
|
/// let mut s = "starlord".to_string();
|
2018-05-17 06:09:58 +00:00
|
|
|
///
|
2019-10-01 11:55:46 +00:00
|
|
|
/// modify_if_u32(&mut x);
|
|
|
|
/// modify_if_u32(&mut s);
|
2018-05-17 06:09:58 +00:00
|
|
|
///
|
2019-10-01 11:55:46 +00:00
|
|
|
/// assert_eq!(x, 42);
|
|
|
|
/// assert_eq!(&s, "starlord");
|
2018-05-17 06:09:58 +00:00
|
|
|
/// ```
|
|
|
|
#[stable(feature = "any_send_sync_methods", since = "1.28.0")]
|
|
|
|
#[inline]
|
|
|
|
pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
|
|
|
|
Any::downcast_mut::<T>(self)
|
|
|
|
}
|
|
|
|
}
|
2015-02-17 10:17:19 +00:00
|
|
|
|
2015-01-15 00:08:07 +00:00
|
|
|
///////////////////////////////////////////////////////////////////////////////
|
|
|
|
// TypeID and its methods
|
|
|
|
///////////////////////////////////////////////////////////////////////////////
|
|
|
|
|
|
|
|
/// A `TypeId` represents a globally unique identifier for a type.
|
|
|
|
///
|
|
|
|
/// Each `TypeId` is an opaque object which does not allow inspection of what's
|
|
|
|
/// inside but does allow basic operations such as cloning, comparison,
|
|
|
|
/// printing, and showing.
|
|
|
|
///
|
|
|
|
/// A `TypeId` is currently only available for types which ascribe to `'static`,
|
|
|
|
/// but this limitation may be removed in the future.
|
2017-01-17 21:56:46 +00:00
|
|
|
///
|
|
|
|
/// While `TypeId` implements `Hash`, `PartialOrd`, and `Ord`, it is worth
|
|
|
|
/// noting that the hashes and ordering will vary between Rust releases. Beware
|
2018-07-03 20:13:49 +00:00
|
|
|
/// of relying on them inside of your code!
|
2017-01-11 02:19:01 +00:00
|
|
|
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
|
2015-01-24 05:48:20 +00:00
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2015-01-15 00:08:07 +00:00
|
|
|
pub struct TypeId {
|
|
|
|
t: u64,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl TypeId {
|
2018-01-30 20:33:33 +00:00
|
|
|
/// Returns the `TypeId` of the type this generic function has been
|
|
|
|
/// instantiated with.
|
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// use std::any::{Any, TypeId};
|
|
|
|
///
|
|
|
|
/// fn is_string<T: ?Sized + Any>(_s: &T) -> bool {
|
|
|
|
/// TypeId::of::<String>() == TypeId::of::<T>()
|
|
|
|
/// }
|
|
|
|
///
|
2019-10-01 11:55:46 +00:00
|
|
|
/// assert_eq!(is_string(&0), false);
|
|
|
|
/// assert_eq!(is_string(&"cookie monster".to_string()), true);
|
2018-01-30 20:33:33 +00:00
|
|
|
/// ```
|
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2019-12-18 17:00:59 +00:00
|
|
|
#[rustc_const_unstable(feature="const_type_id", issue = "41875")]
|
2018-01-30 20:33:33 +00:00
|
|
|
pub const fn of<T: ?Sized + 'static>() -> TypeId {
|
|
|
|
TypeId {
|
2019-08-21 17:56:46 +00:00
|
|
|
t: intrinsics::type_id::<T>(),
|
2018-01-30 20:33:33 +00:00
|
|
|
}
|
|
|
|
}
|
2015-01-15 00:08:07 +00:00
|
|
|
}
|
2019-04-18 02:38:17 +00:00
|
|
|
|
|
|
|
/// Returns the name of a type as a string slice.
|
|
|
|
///
|
|
|
|
/// # Note
|
|
|
|
///
|
|
|
|
/// This is intended for diagnostic use. The exact contents and format of the
|
|
|
|
/// string are not specified, other than being a best-effort description of the
|
|
|
|
/// type. For example, `type_name::<Option<String>>()` could return the
|
|
|
|
/// `"Option<String>"` or `"std::option::Option<std::string::String>"`, but not
|
|
|
|
/// `"foobar"`. In addition, the output may change between versions of the
|
|
|
|
/// compiler.
|
|
|
|
///
|
|
|
|
/// The type name should not be considered a unique identifier of a type;
|
|
|
|
/// multiple types may share the same type name.
|
|
|
|
///
|
|
|
|
/// The current implementation uses the same infrastructure as compiler
|
|
|
|
/// diagnostics and debuginfo, but this is not guaranteed.
|
2019-10-16 16:50:07 +00:00
|
|
|
///
|
2019-11-19 09:18:53 +00:00
|
|
|
/// # Examples
|
2019-10-16 16:50:07 +00:00
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// assert_eq!(
|
|
|
|
/// std::any::type_name::<Option<String>>(),
|
|
|
|
/// "core::option::Option<alloc::string::String>",
|
|
|
|
/// );
|
|
|
|
/// ```
|
2019-04-18 02:38:17 +00:00
|
|
|
#[stable(feature = "type_name", since = "1.38.0")]
|
2019-12-18 17:00:59 +00:00
|
|
|
#[rustc_const_unstable(feature = "const_type_name", issue = "63084")]
|
2019-07-30 03:02:29 +00:00
|
|
|
pub const fn type_name<T: ?Sized>() -> &'static str {
|
2019-04-18 02:38:17 +00:00
|
|
|
intrinsics::type_name::<T>()
|
|
|
|
}
|
2019-11-19 09:18:53 +00:00
|
|
|
|
|
|
|
/// Returns the name of the type of the pointed-to value as a string slice.
|
|
|
|
/// This is the same as `type_name::<T>()`, but can be used where the type of a
|
|
|
|
/// variable is not easily available.
|
|
|
|
///
|
|
|
|
/// # Note
|
|
|
|
///
|
|
|
|
/// This is intended for diagnostic use. The exact contents and format of the
|
|
|
|
/// string are not specified, other than being a best-effort description of the
|
2019-12-15 11:59:02 +00:00
|
|
|
/// type. For example, `type_name_of::<Option<String>>(None)` could return
|
2019-11-19 09:18:53 +00:00
|
|
|
/// `"Option<String>"` or `"std::option::Option<std::string::String>"`, but not
|
|
|
|
/// `"foobar"`. In addition, the output may change between versions of the
|
|
|
|
/// compiler.
|
|
|
|
///
|
|
|
|
/// The type name should not be considered a unique identifier of a type;
|
|
|
|
/// multiple types may share the same type name.
|
|
|
|
///
|
|
|
|
/// The current implementation uses the same infrastructure as compiler
|
|
|
|
/// diagnostics and debuginfo, but this is not guaranteed.
|
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// Prints the default integer and float types.
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// #![feature(type_name_of_val)]
|
|
|
|
/// use std::any::type_name_of_val;
|
|
|
|
///
|
|
|
|
/// let x = 1;
|
|
|
|
/// println!("{}", type_name_of_val(&x));
|
|
|
|
/// let y = 1.0;
|
|
|
|
/// println!("{}", type_name_of_val(&y));
|
|
|
|
/// ```
|
|
|
|
#[unstable(feature = "type_name_of_val", issue = "66359")]
|
2019-12-18 17:00:59 +00:00
|
|
|
#[rustc_const_unstable(feature = "const_type_name", issue = "63084")]
|
2019-11-19 09:18:53 +00:00
|
|
|
pub const fn type_name_of_val<T: ?Sized>(val: &T) -> &'static str {
|
|
|
|
let _ = val;
|
|
|
|
type_name::<T>()
|
|
|
|
}
|