我有多个结构
类型Base struct { Id字符串 名称字符串 代码字符串}type Country struct { 基础 …}类型City struct { 基础 …}我需要做一个……
我已经在评论中发布了这个,但你可以这样做
func myfunc(in interface{}) { switch in.(type) { case []Country: // country logic here case []City: // city logic here } }
看起来你正试图在Go中重新创建类继承。 Go没有故意的类继承。不要试图重新创建它。我相信你在想“国家是基地”。那不对。国家 嵌入视频 一个基地。那不是一回事。这对你如何命名很重要。在这种情况下,似乎“Base”实际上是“位置元数据”,所以我们称之为。
type LocationMeta struct { id string name string code string }
并且您希望界面适用于各种位置。
type Location interface { Id() string Name() string Code() string }
我们可以将LocationMeta符合Location,尽管这可能有点奇怪(是元数据 真 一个位置?)。但它的确有效。
func (b LocationMeta) Id() string { return b.id } func (b LocationMeta) Name() string { return b.name } func (b LocationMeta) Code() string { return b.code }
我们可以在一个城市嵌入LocationMeta:
type City struct { LocationMeta }
而且免费,City现在符合Location。
也就是说,通常你不会为这样一个没有自己逻辑的小东西而烦恼。这真是太过分了;我只是在展示它,因为你似乎正在使用它。通常,您只需遵循每种类型:
type Country struct { id string name string code string } func (c Country) Id() string { return c.id } func (c Country) Name() string { return c.name } func (c Country) Code() string { return c.code }
关于Go的好处在于它并不关心你如何符合界面。城市和国家都以完全不同的方式符合位置,这完全没问题。
所以你可以创建一个城市:
boston := City{LocationMeta{id: "bos", name: "Boston", code: "bos"}}
看看这有多奇怪?由于嵌入对象,我们必须创建一个LocationMeta。它有时是值得的(并且非常强大),但我可能已经完成了Country和Country的乡村方式(没有LocationMeta):
us := Country{id: "us", name: "USA", code: "us"}
但是,它们仍然是位置,所以我们可以将它们放在一个切片中:
locations := []Location{boston, us}
把它们传递给事物:
func printLocations(locations []Location) { fmt.Println(locations) } printLocations(locations)
这个代码的游乐场
游乐场使用嵌入一切
只有结构的更典型方法的游乐场