在Go语言中定义带有嵌入类型的参数类型的函数。

huangapple go评论77阅读模式
英文:

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

问题

非常新手Go语言,可能走错了路。

假设我有一个类型:

type Message struct {
    MessageID string
    typeID    string
}

然后我创建了另一个类型,其中嵌入了Message:

type TextMessage struct {
    Message
    Text       string
}

然后我想创建一个函数,只要它嵌入了Message,就可以接受任何类型:

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

我该如何做到这一点?我的目标是定义一个函数,要求它接受一个具有typeID成员/字段的类型。如果它接受一个接口也可以(但不太理想),在这种情况下,我猜我只需要定义接口,然后定义适当的方法。但除非这是唯一的方法,否则有什么推荐的方法吗?

英文:

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?

答案1

得分: 1

我会选择使用接口的方式:

type TypeIdentifier interface {
    TypeId() string
}

func sendMessage(t TypeIdentifier) {
    id := t.TypeId()
    // 其他操作...
}

你唯一的其他选择是在函数内部进行类型断言,但这很快就会变成一个失控的混乱。

英文:

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.

huangapple
  • 本文由 发表于 2014年11月5日 08:04:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/26747435.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定