The usual way is to use composition :
type Point struct {
x int
y int
}
type CoordinatePoint struct {
Point
other stuff
}
type CartesianPoint struct {
Point
Other methods and fields that aren't relevant
}
Go syntax makes this composition mostly feel like inheritance in other languages. You can for example do this :
cp := CoordinatePoint{}
cp.x = 3
log.Println(cp.x)
And you can call functions taking a Point
as parameter with
doAThingWithAPoint(cp.Point)
To let your points be passed interchangeably, you would have to define an interface
type Pointer interface {
GetPoint() *Point
}
func (cp CoordinatePoint) GetPoint() *Point {
return &cp.Point
}
Then you would be able to define functions taking a Pointer
:
func doSomethingWith(p Pointer) {
log.Println(p.GetPoint())
}
Another solution would be based on an interface defining GetX
, SetX
, GetY
and SetY
but I personally find this approach much heavier and more verbose than necessary.