In a Go project, I've got to define two different kinds of "shapes" to types that implement an interface called MyObject. The shapes themselves are types defined in an external library, and do not implement any shared interface.
MyObject looks like
type MyObject interface {
GetShape() *Shape //some unified return value
}
Shapes look like
type Circle struct {
Radius int
X int
Y int
}
type Square struct {
X int
Y int
W int
H int
}
func NewCircle(x int, y int, radius int) Circle
func NewSquare(x int, y int, w int, h int) Square
I've got a ball and a box that implement MyObject:
type Ball struct {
shape *Circle
}
type Box struct {
shape *Square
}
func (b *Ball) GetShape() *Shape {
return b.shape
}
func (s *Square) GetShape() *Shape {
return s.shape
}
This seems straightforward enough with interfacing - but we can't use one in this situation since there are no methods implemented by Circle and Square that are identical, plus they are outside of the package we're working in.
For methods using the circle and the square, I need to use methods like
testCircleSquare(circle *Circle, square *Square) bool {}
testSquareSquare(square1 *Square, square2 *Square) bool {}
How can I distinguish or make these two objects more generic? The only idea I had so far was to containerize them into a type like
type Shape struct {
circle *Circle
square *Square
}
and check for nil circle or square values to determine which to use, but this seems hacky and difficult to maintain if I add more shapes.