Search code examples
gostructinitializer

Initializing a struct in a struct


This is a slight twist on similar posts.

I have a package called data that has the following:

type CityCoords struct {
    Name string
    Lat float64
    Long float64
}

type Country struct {
        Name string
        Capitol *CityCoords
}

In my main function I try initializing a Country like so:

germany := data.Country {
    Name: "Germany",
    Capitol: {
        Name: "Berlin", //error is on this line
        Lat: 52.5200,
        Long: 13.4050,
    },

}

When I build my project, I get this error aligned with the "Name" attributed as I've flagged above:

missing type in composite literal

How do I resolve this error?


Solution

  • As far as know, * means that an object pointer is expected. So, you could initiate it first using &;

    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)
    }
    

    Or, you can prefer a more elegant way;

    // 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)
    }