Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to subclass in Go

Tags:

oop

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 struct(Circle,Rectangle,etc) that has struct Point as first member. How can I do the same in google go?

like image 532
Nyan Avatar asked Jan 09 '11 16:01

Nyan


People also ask

How do you inherit in go?

Go doesn't have inheritance – instead composition, embedding and interfaces support code reuse and polymorphism.

Does Go language have classes?

Go does not have classes. However, you can define methods on types. A method is a function with a special receiver argument. The receiver appears in its own argument list between the func keyword and the method name.

Does Go support inheritance or generic?

Go does not support inheritance, however, it does support composition. The generic definition of composition is "put together".

What is the subclass?

Definition: A subclass is a class that derives from another class. A subclass inherits state and behavior from all of its ancestors. The term superclass refers to a class's direct ancestor as well as all of its ascendant classes.


2 Answers

Actually, there's a simpler way to do it, which is more similar to the OP's example:

type Point struct {
    x, y int
}

func (p *Point) Move(dx, dy int) {
    p.x += dx
    p.y += 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 notice that Circle would also fulfill the Mover interface that PeterSO posted.

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

like image 69
Ross Light Avatar answered Sep 18 '22 11:09

Ross Light


Although Go has types and methods and allows an object-oriented style of programming, there is no type hierarchy. The concept of “interface” in Go provides a different approach that we believe is easy to use and in some ways more general. There are also ways to embed types in other types to provide something analogous—but not identical—to subclassing. Is Go 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)
}
like image 41
peterSO Avatar answered Sep 18 '22 11:09

peterSO