Skip to content

Instantly share code, notes, and snippets.

@kougazhang
Created January 10, 2022 10:05
Show Gist options
  • Save kougazhang/6808c01fda9f2794e2c703bbb5ccb842 to your computer and use it in GitHub Desktop.
Save kougazhang/6808c01fda9f2794e2c703bbb5ccb842 to your computer and use it in GitHub Desktop.
#golang
type InterfaceA interface {
A()
B()
C()
D()
}
type ImplA struct {
InterfaceA
}
func (ImplA) A() {
fmt.Println("i am implA.A")
}
func (ImplA) B() {
fmt.Println("i am implA.B")
}
func (ImplA) C() {
fmt.Println("i am implA.C")
}
type ImplB struct {
}
func (ImplB) A() {
fmt.Println("i am ImplB.A")
}
func (ImplB) B() {
fmt.Println("i am ImplB.B")
}
func (ImplB) C() {
fmt.Println("i am ImplB.C")
}
func (ImplB) D() {
fmt.Println("i am ImplB.D")
}
func NewImplA(a InterfaceA) ImplA {
return ImplA{InterfaceA: a}
}
func testA(t *testing.T) {
var (
a ImplA
iA InterfaceA
)
// 这一步能够通过编译,说明编译器认为 ImplA 实现了 InterfaceA 的方法
iA = a
iA.D()
// 会抛出 runtime error, 因为 ImplA 没有实现
// panic: runtime error: invalid memory address or nil pointer dereference
}
func testB(t *testing.T) {
ins := NewImplA(ImplB{})
ins.A()
ins.B()
ins.C()
ins.D()
// 输出如下. 这表明方法调用时会调用最浅层的方法.
//i am implA.A
//i am implA.B
//i am implA.C
//i am ImplB.D
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment