methods of child struct is promoted to its parent struct

tags: learning go programming

content

  • methods of child struct is promoted to its parent struct
type Position struct {
    X int
    Y int
}
 
func (p Position) Move(dx, dy int) Position {
    return Position{p.X + dx, p.Y + dy}
}
 
type Player struct {
    Name string
    Position  // embedded
}
 
p := Player{"test", Position{1,1}}
p.Position = p.Move(2,2)

  • in the above example, Move (method of child/inner struct Position) is promoted to parent/outer struct Player

up

down

reference