在结构中初始化结构

时间:2016-11-03 02:57:08

标签: go struct initializer

这在类似的帖子上略有不同。

我有一个名为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

如何解决此错误?

1 个答案:

答案 0 :(得分:3)

据我所知,*表示期望对象指针。因此,您可以先使用&;

启动它
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)
}
相关问题