Expand description
Utilities for dynamic typing or type reflection.
§Any andTypeId
Any itself can be used to get aTypeId, and has more features when usedas a trait object. As&dyn Any (a borrowed trait object), it has theisanddowncast_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, thereis also thedowncast_mut method, for getting a mutable reference to theinner value.Box<dyn Any> adds thedowncast method, which attempts toconvert to aBox<T>. See theBox documentation for the full details.
Note that&dyn Any is limited to testing whether a value is of a specifiedconcrete type, and cannot be used to test whether a type implements a trait.
§Smart pointers anddyn Any
One piece of behavior to keep in mind when usingAny as a trait object,especially with types likeBox<dyn Any> orArc<dyn Any>, is that simplycalling.type_id() on the value will produce theTypeId of thecontainer, not the underlying trait object. This can be avoided byconverting the smart pointer into a&dyn Any instead, which will returnthe object’sTypeId. For example:
usestd::any::{Any, TypeId};letboxed: Box<dynAny> = Box::new(3_i32);// You're more likely to want this:letactual_id = (&*boxed).type_id();// ... than this:letboxed_id = boxed.type_id();assert_eq!(actual_id, TypeId::of::<i32>());assert_eq!(boxed_id, TypeId::of::<Box<dynAny>>());§Examples
Consider a situation where we want to log a value passed to a function.We know the value we’re working on implementsDebug, but we don’t know itsconcrete type. We want to give special treatment to certain types: in thiscase printing out the length ofString values prior to their value.We don’t know the concrete type of our value at compile time, so we need touse runtime reflection instead.
usestd::fmt::Debug;usestd::any::Any;// Logger function for any type that implements `Debug`.fnlog<T: Any + Debug>(value:&T) {letvalue_any = valueas&dynAny;// 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 // different type: just print it out unadorned.matchvalue_any.downcast_ref::<String>() {Some(as_string) => {println!("String ({}): {}", as_string.len(), as_string); }None=> {println!("{value:?}"); } }}// This function wants to log its parameter out prior to doing work with it.fndo_work<T: Any + Debug>(value:&T) { log(value);// ...do some other work}fnmain() {letmy_string ="Hello World".to_string(); do_work(&my_string);letmy_i8: i8 =100; do_work(&my_i8);}Structs§
- TypeId
- A
TypeIdrepresents a globally unique identifier for a type.
Traits§
- Any
- A trait to emulate dynamic typing.
Functions§
- type_
name - Returns the name of a type as a string slice.
- type_
name_ of_ val - Returns the type name of the pointed-to value as a string slice.