Blanket impl and Subset traits (Checking trait impl at runtime)

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.

I just wanted to give a shout out to the rattish (https://crates.io/crates/rattish) crate for dynamically casting trait objects at runtime using a database.

It's not exactly what I was looking for but it's pretty neat. Unfortunately it also depends on some unstable features.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.