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

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