2
这是对类似文章的轻微改动。在结构中初始化一个结构体
我有一个叫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
如何解决此错误?
谢谢,K-Gun。你为什么要从NewCountry和NewCountryCapital返回指向Country和CountryCapital的指针? –
没有具体的理由要做到这一点,您可以根据需要命名该功能。但我认为,在Go世界中,这是一个广泛使用的约定,因为没有'new'关键字来初始化像其他语言中的对象。因此,[Gophers](https://blog.golang.org/gopher)更喜欢用'New'前缀命名函数,并且据我看到它使得它们的代码更具可读性,也更具语义性。 –