1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have 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()
}

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

1
0
1

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?