package main
import "fmt"
type IMessage interface {
Print()
}
type BaseMessage struct {
//IMessage 没有必要embedding这个interface,因为只是按照契约实现接口,但是并没有利用接口的数据和功能
//一般说来直接实现接口的类都没有必要embedding接口
msg string
}
func (message *BaseMessage) Print() {
fmt.Println("baseMessage:msg", message.msg)
}
type SubMessage struct {
BaseMessage //因为要使用BaseMessage的数据,所以必须embedding
}
func (message *SubMessage) Print() {
fmt.Println("subMessage:msg", message.msg)
}
func interface_use(i IMessage) {
i.Print()
}
func main() {
//var message IMessage
//if message == nil {
// fmt.Println("IMessage is nil")
//}
baseMessage := new(BaseMessage)
baseMessage.msg = "a"
interface_use(baseMessage)
SubMessage := new(SubMessage)
SubMessage.msg = "b"
interface_use(SubMessage)
}
转载于:https://my.oschina.net/miros/blog/400848