如何在Go中继承

Nya*_*yan 6 oop go

在CI中可以做这样的事情

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);
Run Code Online (Sandbox Code Playgroud)

使用这种方法,我可以传递任何具有struct Point作为第一个成员的结构(Circle,Rectangle等).我怎么能在谷歌去做同样的事情?

Ros*_*ght 13

实际上,有一种更简单的方法,它更类似于OP的例子:

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)
Run Code Online (Sandbox Code Playgroud)

另请注意,Circle还将实现PeterSO发布的Mover界面.

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


pet*_*rSO 7

尽管Go具有类型和方法,并且允许面向对象的编程风格,但是没有类型层次结构.Go中"接口"的概念提供了一种我们认为易于使用且在某些方面更为通用的不同方法.还有一些方法可以将类型嵌入到其他类型中,以提供类似但不完全相同的子类化.Go是一种面向对象的语言吗?

例如,

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)
}
Run Code Online (Sandbox Code Playgroud)

  • PeterSO的答案是惯用的Go; Go不允许将指针转换为另一个指针,只是将指针强制转换为匹配的接口 - 因此,他定义了一个接口和一些附加到它的类型. (2认同)