这与类似职位略有不同。
我有一个名为的软件包data
,其中包含以下内容:
type CityCoords struct {
Name string
Lat float64
Long float64
}
type Country struct {
Name string
Capitol *CityCoords
}
在我的主要职能中,我尝试像这样初始化一个国家:
germany := data.Country {
Name: "Germany",
Capitol: {
Name: "Berlin", //error is on this line
Lat: 52.5200,
Long: 13.4050,
},
}
当我构建项目时,我得到的错误与上面标记的“名称”对齐:
missing type in composite literal
如何解决此错误?
据了解,这*
意味着需要一个对象指针。因此,您可以先使用&
; 来启动它。
func main() {
germany := &data.Country{
Name: "Germany",
Capitol: &data.CityCoords{
Name: "Berlin", //error is on this line
Lat: 52.5200,
Long: 13.4050,
},
}
fmt.Printf("%#v\n", germany)
}
或者,您可以选择更优雅的方式;
// data.go
package data
type Country struct {
Name string
Capital *CountryCapital
}
type CountryCapital struct {
Name string
Lat float64
Lon float64
}
func NewCountry(name string, capital *CountryCapital) *Country {
// note: all properties must be in the same range
return &Country{name, capital}
}
func NewCountryCapital(name string, lat, lon float64) *CountryCapital {
// note: all properties must be in the same range
return &CountryCapital{name, lat, lon}
}
// main.go
func main() {
c := data.NewCountry("Germany", data.NewCountryCapital("Berlin", 52.5200, 13.4050))
fmt.Printf("%#v\n", c)
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句