Hello everyone, I’m new to Golang. I wanted to try out classes that are composed out of actions. So a player can walk() and fly(), but perhaps a monster can only walk().
In this case both the walk() and fly() methods need to access the position of the player, so I came up with the following code. However I wonder if this is truly Golang idiomatic. A thing I don’t like is that the same pointer is owned by multiple objects.
// You can edit this code!
// Click here and start typing.
package main
import "fmt"
type PositionComponent struct {
x int
y int
}
type Positionable interface {
GetPositionComponent() *PositionComponent
SetPositionComponent(x int, y int)
}
func (p *PositionComponent) GetPositionComponent() *PositionComponent {
return p
}
func (p *PositionComponent) SetPositionComponent(x int, y int) {
p.x = x
p.y = y
}
type Walker struct {
Positionable
}
type Flyer struct {
Positionable
}
func (w *Walker) walk() {
w.GetPositionComponent().x += 1
fmt.Printf("Walked: %s\n", w.GetPositionComponent())
}
func (w *Flyer) fly() {
w.GetPositionComponent().y += 1
fmt.Printf("Flew: %s\n", w.GetPositionComponent())
}
type Player struct {
*PositionComponent
Walker
Flyer
}
func main() {
pComp := PositionComponent{2, 2}
p := Player{&pComp, Walker{&pComp}, Flyer{&pComp}}
p.walk()
p.fly()
fmt.Println(p.PositionComponent)
}