Subclass on google go

In C, I can do something like this

struct Point { int x,y; } struct Circle { struct Point p; // must be first! int rad; } void move(struct Point *p,int dx,int dy) { .... } struct Circle c = .....; move( (struct Point*)&c,1,2); 

Using this approach, I can pass any structure (Circle, Rectangle, etc.) that has a struct Point as the first member. How can i do the same in google go?

+6
oop go
source share
2 answers

Actually, there is an easier way to do this, which is more like an OP example:

 type Point struct { x, y int } func (p *Point) Move(dx, dy int) { px += dx py += dy } type Circle struct { *Point // embedding Point in Circle rad int } // Circle now implicitly has the "Move" method c := &Circle{&Point{0, 0}, 5} c.Move(7, 3) 

Also note that Circle will also run the Mover interface that PeterSO sent.

http://golang.org/doc/effective_go.html#embedding

+11
source share

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) } 
+7
source share

All Articles