GolangNote

Golang笔记

Golang 实现/打印菜单树

Permalink

树结构的菜单,golang 实现的打印效果

Golang 实现/打印菜单树

Go: 树结构的菜单
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package main

import "fmt"

type Org struct {
	OrgID    string
	OrgName  string
	parentID string
}

func printTree(tbl []Org, parent string, depth int) {
	for _, r := range tbl {
		if r.parentID == parent {
			for i := 0; i < depth; i++ {
				fmt.Print("--")
			}
			fmt.Print(r.OrgName, "\n\n")
			printTree(tbl, r.OrgID, depth+1)
		}
	}
}

func main() {
	data := []Org{
		{"A001", "Dept", "0 -----th top"},
		{"A002", "subDept1", "A001"},
		{"A003", "sub_subDept", "A002"},
		{"A006", "gran_subDept", "A003"},
		{"A004", "subDept2", "A001"},
	}

	printTree(data, "0 -----th top", 0)
}

输出:

plaintext: 树结构的菜单
1
2
3
4
5
6
7
8
9
Dept

--subDept1

----sub_subDept

------gran_subDept

--subDept2

摘自 https://play.golang.org/p/27CQAhI8gf

Related articles

Golang实现简单的Socks5代理

Socks5 代理较 `http/https` 代理有较好的性能,下面是借鉴某个著名开源软件的 local 实现的简单代理。...

Golang phantomjs 动态代理实现

phantomjs 是个很优秀的软件,虽然现在被chrome headless 抢了风头,但在某些特定场合,使用phantomjs 还是很方便,这里是介绍使用Go 实现动态代理。...

Write a Comment to "Golang 实现/打印菜单树"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.16.5 Processed in 0ms