简体   繁体   中英

Define function with parameter whose type has an embedded type in Go

Very new to Go and so probably going about this the wrong way.

Let's say I have a type:

type Message struct {
    MessageID string
    typeID    string
}

And I create another type with Message embedded:

type TextMessage struct {
    Message
    Text       string
}

And then I want to create a function that will take any type, so long as it has Message embedded:

func sendMessage(???===>msg Message<===???) error

How do I do that? My goal is to define the function such that it requires a type with a typeID member/field. It would be ok (but less desirable) if it took an interface, in which case I assume I'd just define the interface and then define the appropriate method. But unless that's the only way to accomplish this - what's the recommended approach?

I would go the interface route:

type TypeIdentifier interface {
    TypeId() string
}

func sendMessage(t TypeIdentifier) {
    id := t.TypeId()
    // etc..
}

Your only other option is to type assert an interface{} within the function.. which will quickly become an out-of-control bowl of bolognese.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM