type msgPayload interface {
MsgPayload()
}
type UnionAAndBMessage struct {
Payload msgPayload
}
type MsgA struct {
A int
}
func (a *MsgA) MsgPayload() {
fmt.Printf("msga : %v\n", a.A)
}
type MsgB struct {
B int
}
func (a *MsgB) MsgPayload() {
fmt.Printf("msgb : %v\n", a.B)
}
// 联合体传参
func printMsg(m UnionAAndBMessage) {
// 调用接口函数
m.Payload.MsgPayload()
// 根据类型分类处理
switch m.Payload.(type) {
case *MsgA:
fmt.Printf("*msga\n")
case *MsgB:
fmt.Printf("*msgb\n")
}
}
func main() {
msgA := UnionAAndBMessage{
&MsgA{
A: 123,
},
}
msgB := UnionAAndBMessage{
&MsgB{
B: 345,
},
}
printMsg(msgA)
printMsg(msgB)
}
go: 实现联合体
最新推荐文章于 2024-07-12 08:36:25 发布