as_any_min/lib.rs
1//! This is a very minimal crate that makes it easier to work
2//! with traits that implement `Any` by allowing you to easily
3//! upcast to it.
4//!
5//! # Example
6//!
7//! ```
8//! use core::any::Any;
9//! use as_any_min::AsAny;
10//!
11//! struct MyStruct;
12//! trait MyTrait {}
13//! impl MyTrait for MyStruct {}
14//!
15//! /* Note that AsAny is automatically implemented for all
16//! structs that implement Any, so there is no need to
17//! implement it manually (in fact it won't compile if
18//! you try to) */
19//!
20//! fn main() {
21//! // my_variable is now a trait object, which is the
22//! // main use case for the AsAny trait.
23//! let my_variable: &dyn MyTrait = &MyStruct;
24//!
25//! let my_any_variable: &dyn Any = my_variable.as_any();
26//! }
27//! ```
28//!
29//! # Without Using `AsAny`
30//!
31//! Since rust doesn't (currently) have any built in way to
32//! upcast from a trait object to another trait (such as `Any`),
33//! this won't compile.
34//!
35//! ```compile_fail
36//! use core::any::Any;
37//!
38//! struct MyStruct;
39//! trait MyTrait {}
40//! impl MyTrait for MyStruct {}
41//!
42//! fn main() {
43//! let my_variable: &dyn MyTrait = &MyStruct;
44//!
45//! let my_any_variable: &dyn Any = my_variable;
46//! }
47//! ```
48
49#![no_std]
50#![warn(missing_docs)]
51
52use core::any::Any;
53
54/// This trait allows anything that implements `Any` to be easily
55/// upcast to `Any`.
56///
57/// It is automatically implemented for all structs that implement
58/// `Any`. This is useful because there isn't an automatic way to
59/// upcast a trait object.
60pub trait AsAny {
61 /// This returns the struct as a `&dyn Any`
62 fn as_any(&self) -> &dyn Any;
63
64 /// This returns the struct as a `&dyn mut Any`
65 fn as_any_mut(&mut self) -> &mut dyn Any;
66}
67
68impl<T> AsAny for T
69 where T: Any
70{
71 fn as_any(&self) -> &dyn Any {
72 self
73 }
74 fn as_any_mut(&mut self) -> &mut dyn Any {
75 self
76 }
77}