go to mimic C ++ virtual functions and pure virtual functions

 
 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

 

Look at the code to understand what may be wrong, please correct me
A interface {} there will be a default implementation, if you want to use this simple point that contains the default interface {} implements all interfaces struct {} calls will call the default method, if a method of operating a different only we need to implement a different approach, you can, when you call a method call will be implemented,
If you say that what is simple and is similar to C ++ pure virtual function
As it will be appreciated, multi-state operation when implemented in C ++,

Guess you like

Origin www.cnblogs.com/--just-lbk/p/11117802.html