Goの構造体の初期化パターン

1 min読了の目安(約900字TECH技術記事

CustomerAの書き方のほうがシンプルになる。ネストがもっと深くなるとCustomerBの書き方はかなりつらい。。

package main

import (
	"fmt"
)

type CustomerA struct {
	Name 		string
	Email 		string
	Tell 		string
	Addresses 	[]AddressA
}

type AddressA struct {
	Prefecture 		string
	City 			string
}

type CustomerB struct {
	Name 		string
	Email 		string
	Tell 		string
	Addresses 	[]struct {
		Prefecture string
		City string
	}
}

func main() {
	ca := CustomerA{
		Name:      "Taro Yamada",
		Email:     "yamada@example.com",
		Tell:      "03-0000-0000",
		Addresses: []AddressA{
			{Prefecture: "tokyo", City: "Setagaya"},
			{Prefecture: "tokyo", City: "Setagaya"},
		},
	}
	cb := CustomerB{
		Name:  "nanashi",
		Email: "nanashi@example.com",
		Tell:  "090-0000-0000",
		Addresses: []struct {
			Prefecture string
			City       string
		}{
			{Prefecture: "Yamagata", City: "aaa"},
			{Prefecture: "Yamagata", City: "aaa"},
		},
	}
	fmt.Println(ca)
	fmt.Println(cb)
}