golang-利用Embedding和interface实现多态

go没有继承,但有个Embedding,这个东西有点类似于组合,写了个小例子,实现多态的效果

 

 

 

package main

import "fmt"

type IMessage interface{
	Print()
}

type BaseMessage struct{
	msg string
}

func (message *BaseMessage) Print(){
	fmt.Println("baseMessage:msg",message.msg)
}

type SubMessage struct{
	BaseMessage
}

func main() {
	var message IMessage
	baseMessage := new(BaseMessage)
	baseMessage.msg = "a"
	message = baseMessage
	message.Print()
	SubMessage := new(SubMessage)
	SubMessage.msg = "b"
	message = SubMessage
	message.Print()
	
	
}

 

输出:

baseMessage:msg a

baseMessage:msg b

 

 

你可能感兴趣的:(Go)