2 回答

TA貢獻1829條經(jīng)驗 獲得超4個贊
看起來您正在嘗試在 Go 中重新創(chuàng)建類繼承。Go 故意沒有類繼承。不要試圖重新創(chuàng)建它。我相信您在想“國家是基地”。那是不正確的。國家嵌入基地。那不是一回事。這對你如何命名事物很重要。在這種情況下,“基地”似乎真的是“位置元數(shù)據(jù)”,所以我們就這樣稱呼它。
type LocationMeta struct {
id string
name string
code string
}
而且您需要一個適用于各種位置的界面。
type Location interface {
Id() string
Name() string
Code() string
}
我們可以使 LocationMeta 符合 Location,盡管這可能有點奇怪(元數(shù)據(jù)真的是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 現(xiàn)在符合 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 的偉大之處在于它不關(guān)心你如何符合接口。City 和 Country 都以完全不同的方式符合 Location,這完全沒問題。
所以你可以創(chuàng)建一個城市:
boston := City{LocationMeta{id: "bos", name: "Boston", code: "bos"}}
看看這有多奇怪?由于嵌入對象,我們必須創(chuàng)建一個 LocationMeta。有時它是值得的(而且非常強大),但我可能會以鄉(xiāng)村方式(沒有 LocationMeta)完成城市和鄉(xiāng)村:
us := Country{id: "us", name: "USA", code: "us"}
但是,它們都是位置,因此我們可以將它們放在一個切片中:
locations := []Location{boston, us}
并將它們傳遞給事物:
func printLocations(locations []Location) {
fmt.Println(locations)
}
printLocations(locations)

TA貢獻1850條經(jīng)驗 獲得超11個贊
我已經(jīng)在評論中發(fā)布了這個,但你可以這樣做
func myfunc(in interface{}) {
switch in.(type) {
case []Country:
// country logic here
case []City:
// city logic here
}
}
- 2 回答
- 0 關(guān)注
- 171 瀏覽
添加回答
舉報