Hello, I'm looking for a pattern where I can create traits that variously overlap each other and conveniently manipulate the trait objects at runtime. I can see how it'd be possible with Specialization, but is there a way to do it with the current feature set?
For example:
use num_traits::{*};
trait MyNum {
fn try_as_int(&self) -> Option<&dyn MyInt>;
fn try_as_float(&self) -> Option<&dyn MyFloat>;
}
impl <T> MyNum for T where T:Num {
//Is it possible to implement these without specialization, and
// keeping the blanket implementation on all Num (as opposed to
// multiple implementations for PrimInt, Float, etc.?
fn try_as_int(&self) -> Option<&dyn MyInt> {None}
fn try_as_float(&self) -> Option<&dyn MyFloat> {None}
}
trait MyInt : MyNum {
fn print_stuff(&self);
}
impl <T> MyInt for T where T:PrimInt {
fn print_stuff(&self) {
println!("It's an Int!");
}
}
trait MyFloat : MyNum {
fn print_stuff(&self);
}
impl <T> MyFloat for T where T:Float {
fn print_stuff(&self) {
println!("It's a Float!");
}
}
fn main() {
5.print_stuff();
let five : Box<dyn MyNum> = Box::new(5);
five.try_as_int().unwrap().print_stuff();
}
The Any
trait provides downcast_ref
If I knew a concrete type that the box contained, but I'm not sure how to go from one boxed trait object to another boxed trait object of a different trait without knowing what concrete type is contained in the box.
Is there any other project that uses a pattern like this?
Thank you for any thoughts.