go struct的嵌套/组合以及interface

版权声明:本文为博主原创文章,转载时请务必注明本文地址, 禁止用于任何商业用途, 否则会用法律维权。 https://blog.csdn.net/stpeace/article/details/84136563

      看代码:

package main 
import "fmt"

type Intf interface {
	process()
}

type MsgBase struct {
	id int
}

func (p *MsgBase) process() {
	fmt.Printf("base %v\n", p)
}

type Msg1 struct {
	MsgBase
	x int
}

type Msg2 struct {
	MsgBase
	x int
	y int
}

func (p *Msg1) process() {
	fmt.Printf("business %v\n", p)
}

func main() {
	var m Intf = new(Msg1)   // 不能用var m MsgBase = new(Msg1)
	m.process()

	m = new(Msg2)
	m.process()
}

         结果:

business &{{0} 0}
base &{0}

  

        不多收。

猜你喜欢

转载自blog.csdn.net/stpeace/article/details/84136563