golang 组成树形格式

该封装受到前端 js filter函数的启发看着特别简洁

一、封装一个函数

比较简单就是循环根据传入的 回调函数 进行过滤组成新的数组返回

func Filter[T any](arr []*T, f func(item *T) bool) (list []*T) {
	for _, el := range arr {
		if f(el) {
			list = append(list, el)
		}
	}
	return list
}

二、封装通用的树形方法

第一层先过滤出父级 第二层过滤出子级 如果子及存在那就就加到父级的Children中

type Tree[T any] interface {
	GeteIsQual(father *T, childId *T) bool
	SetChild(father *T, branchArr []*T)
	RetFather(father *T) bool
}
func ToTree[T any](list []*T, fun Tree[T]) []*T {
	return Filter(list, func(index int, father *T) bool {
		branchArr := Filter(list, func(i int, childId *T) bool {
			return fun.GeteIsQual(father, childId)
		})

		if len(branchArr) > 0 {
			fun.SetChild(father, branchArr)
		}
		return fun.RetFather(father)
	})
}

使用

package main

func main (){
	type Dept struct {
		id
		DeptName string  `json:"deptName"`
		Remark   string  ` json:"remark"`
		ParentId string  ` son:"parentId"`
		Children []*Dept `json:"children"`
	}
	func (d *Dept) GeteIsQual(father *Dept, childId *Dept) bool {
		return father.Id == childId.ParentId
	}
	func (d *Dept) SetChild(father *Dept, branchArr []*Dept) {

		father.Children = branchArr
	}
	func (d *Dept) RetFather(father *Dept) bool {
	// 顶级的ParentId这块可以看一下保存的时候ParentId 默认值是多少
		return father.ParentId == "0"
	}
	dept := []models.Dept{}
	// dept 是数据库查出来的数据这块就不展示了
	list = ToTree[Dept ](dept , &models.dept{})
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值