Trying to solve some puzzles to learn better Rust. The problem I am trying to solve would be trivial with method/function overloading in C++ and I get it that in Rust you are supposed to use traits to do this type of thing, but I cannot seem to wrap my head around it. So, in my puzzle there are boxes and stacks of boxes and the operation I am trying to implement is stacking something on top of a given box. The something could be another box or a stack of boxes. If function overloading was a thing I would do
struct Bx { ... }
impl Bx {
fn stack(self, x: Bx) -> Option<Vec<Bx>> { ... }
fn stack(self, x: Vec<Bx>) -> Option<Vec<Bx>> { ... }
}
but that is not a thing, so I tried a different approach
struct Bx { ... }
trait Stackable {}
impl Stackable for Bx {}
impl Stackable for Vec<Bx> {}
impl Bx {
fn stack<T: Stackable> -> Option<Vec<Bx>> {
/* but now I don't know what to do since I don't know what T is */
}
}
but the implementation is different for a single box and a stack of boxes and I cannot match on type.
I could reverse the logic and implement "something gets stacked on top of a box", so that stack()
is a method on both the box and the stack and the box being stacked on is passed as an argument, but that makes some of my other logic ass-backwards. I would really like to have a stack()
method on the box and pass the thing getting stacked on top of it as an argument. What am I missing?