2

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?

1 Answer 1

3

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)
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, K-Gun. Why do you return pointers to Country and CountryCapital from NewCountry and NewCountryCapital?
There is no specific reason to do that, you can name that functions as you want. But I think, in Go world, this is a widely used convention just because of there is no new keyword to initialize an object like in other languages. So, Gophers prefer that way by naming functions with New prefix and as far as I see it is making their code more readable, also semantic.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.