2016-11-03 29 views
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, 
    }, 

} 

私は私のプロジェクトをビルドするとき、私はこれを取得私が上記にフラグを立てた「名前」と一致しているエラー:

このエラーを解決するにはどうすればよいですか?

答えて

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

ありがとう、Kガン。なぜあなたはNewCountryとNewCountryCapitalからCountryとCountryCapitalへのポインタを返すのですか? –

+0

特別な理由はありませんが、その機能の名前を自由に設定できます。しかし、Goの世界では、他の言語のようにオブジェクトを初期化するための 'new'キーワードがないため、これは広く使われている規約です。ですから、[Gophers](https://blog.golang.org/gopher)は、 'New'接頭辞を付けて関数の名前を付けることで、そのコードを読みやすく、セマンティックなものにしています。 –

関連する問題