1

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?

4
  • Interface - definitely. Your other option is to accept an interface and type assert it in the function .. but thats icky-pants when there's a more type-safe way. Commented Nov 5, 2014 at 0:06
  • ...by "accept an interface" above.. I meant interface{}. Commented Nov 5, 2014 at 0:19
  • Ok, that's not so bad after I try it out. Wanted to make sure I wasn't missing some obvious modality. Make it an answer so I can accept? Commented Nov 5, 2014 at 0:46
  • @4of4: You don't need to change every single instance of Golang to go. It's not important, and both are acceptable names (as seen in the tag wiki excerpt). Commented Nov 8, 2014 at 0:13

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

At first, the function seemed like overkill. But once I got past that it flows nicely and allows the typeID to stay out sight, like I'd prefer.
More and more I find myself defining interfaces for this purpose and the code - although more of it - becomes much more finely tuned and clean. Everything just has small specific purposes and it flows nicely.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.