0
Help us understand the problem. What are the problem?

More than 1 year has passed since last update.

Organization

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

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

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

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Sign upLogin
0
Help us understand the problem. What are the problem?