Can I call multiple (sub)trait default methods from a supertrait?

I've seen how one does one default subtrait method, but what if I want to use multiple subtraits, all with their own default method?

Your playground example doesn't actually include any supertraits, did you mean to make CalculateType a supertrait of CalculateI32 and CalculateF64?

In any case, it looks like you are trying to implement dynamic typing by creating a method to identify the output type. I don't think that is going to be possible to implement using traits, but since you are already using Any you don't need to implement this yourself and can just use Any::type_id. Although since you are then going on to print the value, you probably want to downcast it instead of just checking its identifier.

1 Like

My apologies. No CalculateType being the supertrait of Calculate.
But the idea is the same.

trait Calculate: CalculateType {
    fn calculate(&self) -> Box<dyn Any>;
}

I'm having a bit of trouble understanding what you're trying to do, but I managed to tweak your code into something that compiles; maybe that will help.

1 Like

That's exactly what I was looking for.
Type checking on a limited amount of types, that one can neatly put into a match statement.
I just prefer match statements over if/else statements anytime I can.

Thank you.

For that, the standard tool is an enum:

pub enum Answer {
    I32(i32),
    F64(f64)
}

trait Calculate {
    fn calculate(&self) -> Answer;
}

// ...

fn main() {
    let mut calculations: Vec<Box<dyn Calculate>> = Vec::new();
    calculations.push(Box::new(Square(42.0)));
    calculations.push(Box::new(AddInt { lhs: 13, rhs: 12 }));
    
    for calculation in calculations {
        match calculation.calculate() {
            Answer::I32(x) => println!("i32: {x:?}"),
            Answer::F64(x) => println!("f64: {x:?}"),
        }
    }
}
5 Likes