Michael
Michael

Reputation: 4090

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?

Upvotes: 1

Views: 59

Answers (1)

Simon Whitehead
Simon Whitehead

Reputation: 65059

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.

Upvotes: 1

Related Questions