Although Go has types and methods and allows object-oriented programming style, there is no type hierarchy. The concept of "interface" in Go provides a different approach, which we believe is easy to use and in some ways more general. These are also ways to embed types in other types, something similar but not identical to a subclass. Is there an object oriented language ?, FAQ.
For example,
package main import "fmt" type Mover interface { Move(x, y int) } type Point struct { x, y int } type Circle struct { point Point rad int } func (c *Circle) Move(x, y int) { c.point.x = x c.point.y = y } type Square struct { diagonal int point Point } func (s *Square) Move(x, y int) { s.point.x = x s.point.y = y } func main() { var m Mover m = &Circle{point: Point{1, 2}} m.Move(3, 4) fmt.Println(m) m = &Square{3, Point{1, 2}} m.Move(4, 5) fmt.Println(m) }
peterSO
source share