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

3000文字Tips - 知ると便利なTipsをみんなへ届けよう
https://qiita.com/official-events/d523df99d6479293ffa7

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?