🦁

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

2020/10/13に公開

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

Discussion