9. 実例:time (Windows タイムゾーン変換 map 生成)
var abbrs = map[string]abbr{
"Egypt Standard Time": {"EET", "EET"}, // Africa/Cairo
"Morocco Standard Time": {"+00", "+01"}, // Africa/Casablanca
"South Africa Standard Time": {"SAST", "SAST"}, // Africa/Johannesburg
"Sudan Standard Time": {"CAT", "CAT"}, // Africa/Khartoum
...
<supplementalData>
<version number="$Revision$"/>
<windowsZones>
<mapTimezones otherVersion="7e11200" typeVersion="2019b">
...
<!-- (UTC+02:00) Cairo -->
<mapZone other="Egypt Standard Time" territory="001" type="Africa/Cairo"/>
<mapZone other="Egypt Standard Time" territory="EG" type="Africa/Cairo"/>
...
Windowsタイムゾーン仕様
windowsZones.xml
生成された map リテラル
zoneinfo_abbrs_windows.go
//go:generate env ZONEINFO=$GOROOT/lib/time/zoneinfo.zip go run genzabbrs.go -output zoneinfo_abbrs_windows.go
//go:generate を含む zoneinfo.go
10. 実例:stringer (const の型に String() メソッド生成)
const _Pill_name = "PlaceboAspirinIbuprofenParacetamol"
var _Pill_index = [...]uint8{0, 7, 14, 23, 34}
func (i Pill) String() string {
if i < 0 || i >= Pill(len(_Pill_index)-1) {
return "Pill(" + strconv.FormatInt(int64(i), 10) + ")"
}
return _Pill_name[_Pill_index[i]:_Pill_index[i+1]]
}
type Pill int
const (
Placebo Pill = iota
Aspirin
Ibuprofen
Paracetamol
Acetaminophen = Paracetamol
)
//go:generate go run golang.org/x/tools/cmd/stringer -type=Pill
Pill の String() メソッドが
生成された pill_string.go
Pill 型の const 定義と
//go:generate を含む pill.go
go run で呼び出す
stringer コマンド
11. Go のコード生成を深く知るための資料
● 自由度が高いゆえにわかりにくい・まちがいやすい
● go generate のマニュアルを読む
○ https://golang.org/cmd/go/#hdr-Generate_Go_files_by_processing_source
○ go help generate で読める
● go generate 登場時の記事を読む (Go 1.4 の頃; 2014 年末)
○ The Go Blog: Generating code https://blog.golang.org/generate
■ stringer を例として詳しく説明している
○ Go ganerate: A proposal https://golang.org/s/go1.4-generate
12. go generate のベストプラクティス
● Go Modules など、最近の Go に導入さ
れた機能を踏まえたコード生成のベスト
プラクティスをまとめました
● このスライドで紹介した実例についての
追加のトピックもあります
● 今後も内容は随時更新
本日も更新しました!
https://qiita.com/yaegashi/items/d1fd9f7d0c75b2bb7446