Trait objects and downcast - a use case suggestion

So I have the following use case where I would like to store so structs as a Box<Trait> but still be able some time place down the line be able to downcast it to the actual concrete type (I will know what the type is). Let me explain the use case and maybe someone could point me out to how to do this, or how to do it in a better way. I'm implementing a compiler which has similar to an SSA representation. Each node in the DAG is bound to an Operator trait which based on the inputs of the operator populates what are the outputs node properties (e.g. data type, size, and some specific things related to my compiler like is it differentiable, does it depends on inputs etc..). Now the operator trait has this methods defined. The thing is that each specific operator could have extra arguments. E.g.

struct ReduceSum{
axis: u8
}

struct ConstantInput {
data_type: TypeEnum,
shape: Shape
}

impl Operator for ReduceSum{
\\ ... 
}

impl Operator for ConstantInput {
\\ ,,
}

My SSA is implemented as Node in something like this:

struct Node {
op: Box<Operator>,
data_type: TypeEnum,
shape: Shape,
is_differentiable: bool,
is_input_dependent: bool
\\ ...
}

The Operator has a corresponding method for returning a Node given all of its inputs. However, the backend, which will generate low level code would need to have access to the arguments (like axis in ReduceSum) in order to generate the corresponding gpu kernel. If we assume that each Operator has a name which uniquely identifies it it would mean that the backend will know what is the correct type of the Operator. The question is how to down cast it to the concrete type, or probably even better - how to abstract this use case better.

You mean as in Box::downcast?

2 Likes

Hmm, strange how I did not see that before, must have seen been looking at the wrong place or something, but yes I guess that solves my purpose.

1 Like