DRYな備忘録

Don't Repeat Yourself.

(メモ)Go言語のinvalid recursive typeエラー、再帰データ型の実装とイテレーションについて

jsonでいうとこんな感じの

{
    "id": 48,
    "name": "foo",
    "entry": {
        "id": 36,
        "name": "bar",
        "entry": {
            "id": 24,
            "name": "baz",
            "entry": {
                "id": 12,
                "name": "qux"
            }
        }
    }
}

問題

コンパイル時のinvalid recursive typeエラーは、ポインタ型にすれば解決 invalid recursive type in a struct in go - Stack Overflow

実装

package main

import (
    "encoding/json"
    "fmt"
    "strings"
)

const data = `{
  "id": 48,
  "name": "foo",
  "entry": {
      "id": 36,
      "name": "bar",
      "entry": {
          "id": 24,
          "name": "baz",
          "entry": {
              "id": 12,
              "name": "qux"
          }
      }
  }
}`

type Entry struct {
    ID    int    `json:"id"`
    Name  string `json:"name"`
    Child *Entry `json:"entry"`
}

func main() {

    root := new(Entry)
    if err := json.NewDecoder(strings.NewReader(data)).Decode(root); err != nil {
        panic(err)
    }

    for entry := root; entry.Child != nil; entry = entry.Child {
        fmt.Printf("%s has a child: %+v\n", entry.Name, entry.Child)
    }
}

https://play.golang.org/p/vBNfDuhLHB

参考

雑感

Go言語によるWebアプリケーション開発

Go言語によるWebアプリケーション開発