代码示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package main

import "fmt"

type MyInterface interface {
Check() bool
Do()
}

type Abstract struct {
MyInterface
}

func (a *Abstract) Do() {
fmt.Println(a.Check())
}

type Impl struct {
*Abstract
}

func NewImpl() *Impl {
a := &Abstract{}
i := &Impl{a}
a.MyInterface = i
return i
}

func (i *Impl) Check() bool {
return true
}

func main() {
impl := NewImpl()
impl.Do()
}

其实结构体里套接口实际是一个匿名字段,而new时候做的事就是把子类实例自身传进去,好让继承的父类方法能够调用到子类实现的方法。


参考:oop - How to implement an abstract class in Go? - Stack Overflow