2 回答

TA貢獻1880條經驗 獲得超4個贊
你可以嵌入Planet到PlanetWithMass:
type PlanetWithMass struct {
? ? Planet
? ? Mass float64
}
并做類似的事情
marsWithMass := PlanetWithMass{
? ? Planet: mars,
? ? Mass: 639e21,
}

TA貢獻1804條經驗 獲得超8個贊
您可能可以使用map[string]string,這將使您能夠顯式添加盡可能多的子鍵。注意:您必須首先使用一種類型聲明結構
type PlanetWithMass struct { Planet map[string]string }
然后添加更多字段,從結構的一個實例開始
type PlanetWithMass struct {
Planet map[string]string
}
planet := &PlanetWithMass{} // instance of struct
planet.Planet = make(map[string]string) // declare field as a map[string]string
planet.Planet["Name"] = "Mercury"
planet.Planet["Galaxy"] = "Milky Way"
planet.Planet["Population"] = "7 Billion"
planet.Planet["HasOceans"] = "Yes"
使用這種方法,您可以將多個字段添加到結構中,而無需擔心使用接口。這可能是一個全面的黑客,但它的工作原理!
- 2 回答
- 0 關注
- 262 瀏覽
添加回答
舉報