3 ms·
I think what he actually wanted was: type Shape struct { Rectangle *Rectangle Circle *Circle Triangle *Triangle }
by jrockway 12y ago
I think what he actually wanted was:
type Shape struct {
Rectangle *Rectangle
Circle *Circle
Triangle *Triangle
}
Then you send shapes on your channel rather than interface {}. If you want to enforce having only one element populated, make the struct members private and write:
func NewRectangleShape(r *Rectangle) *Shape {
return &Shape{rectangle: r}
}
- 1_player 12y agoNo, please don't. Go structs are not C unions. Please see my other comment in this thread about using Go interfaces.
- jrockway 12y agoI disagree. Sometimes an interface is not appropriate; just because you have two things that are alike doesn't mean that they implement an interface. "A circle, triangle, or rectangle" is not the same data structure as "Something that can be drawn". Certainly if you have a function that draws something given a Draw() method, having the function take a "Drawable" is appropriate. But it's not the only use case; sometimes you really mean "A circle, triangle, or rectangle" and in that case, a struct is absolutely what you want.