DRYな備忘録

Don't Repeat Yourself.

【Go言語】無名structの初期化

しれっと可能だったのでメモ

The Go Playground

package main

import (
    "encoding/json"
    "fmt"
)

func main() {

    // 無名structの初期化
    dest := &struct {
        Name  string   `json:"name"`
        Age   int      `json:"age"`
        Langs []string `json:"langs"`
    }{}

    json.Unmarshal([]byte(res), dest)
    fmt.Printf("%+v\n", dest)
}

var res = `{
    "name": "otiai10",
    "age" : 29,
    "langs": ["go","js","python"]
}`

APIのhttpレスポンスに近いところのテスト書いてて、tmpなstructにresponseをmapしたいときなんかで、くそ真面目にtype宣言してられるか、っていうときまあ便利だった

参考: 10 things you (probably) don't know about Go

DRYな備忘録

スターティングGo言語

スターティングGo言語

改訂2版 基礎からわかる Go言語

改訂2版 基礎からわかる Go言語