2015-08-18

構造体に埋め込みがある場合のフィールド名

golangで構造体を初期化する際に、
フィールド名を付けた方式で書きたいのだが、
埋め込んだフィールドの取り扱いが
ざっと調べても見つからなかった。

tl; dr
    型名を使う。

type Animal struct {
    Name string
}
type Dog struct {
    *Animal
    Age int
}

という構成で、

d := &Dog{
    new(Animal),
    Age: 10,
}

と書くと「mixture of field:value and value initializers」
というコンパイルエラーになる。
埋め込みフィールドのフィールド名がわからないのだが、
単に型名を書くので良いらしい。

d := &Dog{
    Animal: new(Animal),
    Age: 10,
}

No comments:

Post a Comment