1

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?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Mad Wombat
  • 14,490
  • 14
  • 73
  • 109
  • 2
    The duplicate [applied to your situation](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=0d4796ce44c7fcaaf770d82ed4b94f07). – Shepmaster Jan 08 '20 at 18:05
  • Thank you. In your implementation though, wouldn't stack() method have trouble resolving, since there are two separate implementations for Bx? – Mad Wombat Jan 08 '20 at 18:14
  • It's probably not a great idea to have them named the same, you are right, but it should work as intended here, I think. You can handle the case if they are named the same though ([How to call a method when a trait and struct use the same method name?](https://stackoverflow.com/q/44445730/155423)). – Shepmaster Jan 08 '20 at 18:21
  • [Here's another option using a generic trait](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=292d69a7fba5165916e2e8fd7439e02e). In general I don't usually see the utility of function overloading, preferring to have separate `stack` and `stack_all` methods unless I need to write generic code. – trent Jan 08 '20 at 20:01

0 Answers0