LoginSignup
0
0

More than 1 year has passed since last update.

Golangサンプルコード: 構造体の情報を再帰的に読む

Posted at

構造体を再帰的に読んでいく。
無限ループに陥らないようにチェックを入れた。

package main

import "fmt"

type Node struct {
    ID    int
    Child *Node
}

func (n *Node) PrintID() {
    check := map[int]bool{}
    var printID func(n *Node)
    printID = func(n *Node) {
        fmt.Printf("%d\n", n.ID)
        check[n.ID] = true
        if n.Child != nil {
            if _, done := check[n.Child.ID]; !done {
                printID(n.Child)
            }
        }
    }
    printID(n)
}

func main() {

    n1 := Node{ID: 1}
    n2 := Node{ID: 2}
    n3 := Node{ID: 3}

    n1.Child = &n3
    n2.Child = &n1
    n3.Child = &n2

    n := Node{ID: 4, Child: &n1}
    n.PrintID()
}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0