go 模仿C++虚函数,纯虚函数

 
 1 package main
 2 
 3 import (
 4     "fmt"
 5 )
 6 
 7 type Intf interface {
 8     process()
 9 }
10 
11 type MsgBase struct {
12     id int
13 }
14 
15 func (p *MsgBase) process() {
16     fmt.Printf("base %v\n", p)
17 }
18 
19 type Msg1 struct {
20     *MsgBase
21     x int
22 }
23 
24 type Msg2 struct {
25     *MsgBase
26     x int
27     y int
28 }
29 
30 func (p *Msg1) process() {
31     fmt.Printf("business %v\n", p)
32 }
33 
34 func main() {
35     m := &Msg1{} //
36     m.process()
37 
38     n := &Msg2{}
39     n.process()
40 }
View Code
看代码理解一下 可能不对,欢迎指正
一个interface{} 会有一个 默认的实现,如果你想要简单点使用这个 interface{} 包含默认的实现了所有接口的 struct{} 调用就会调用默认的方法,如果某一个方法的操作是不同的,只需要实现不同的方法,即可,调用的时候就会调用你实现的方法,
如果要说是啥,就是简单,类似的就是 C++的纯虚函数
可以理解为,C++实现的运行时多态 ,

猜你喜欢

转载自www.cnblogs.com/--just-lbk/p/11117802.html