为什么在实现层次树时值会被覆盖?

huangapple go评论82阅读模式
英文:

golang why is value overwritten while implementing hierarchy tree?

问题

package main

import (
	"encoding/json"
	"fmt"
)

type employee struct {
	Name      string      `json:"name"`
	Id        int         `json:"id,omitempty"`
	ManagerId int         `json:"managerid"`
	Reporters []employee `json:"reporters,omitempty"`
}

type EmployeeList struct {
	employees map[int]employee
	root      employee
}

func NewEmployeeList() *EmployeeList {
	var el EmployeeList
	el.employees = make(map[int]employee)
	return &el
}

func (el *EmployeeList) CreateMap(employeesInfo []employee) {
	for _, emp := range employeesInfo {
		e := employee{
			Name:      emp.Name,
			Id:        emp.Id,
			ManagerId: emp.ManagerId,
		}
		el.employees[emp.Id] = e
		if emp.ManagerId == 0 {
			el.root = e
			fmt.Println("CreateMap", el.root)
		}
	}
	fmt.Println("CreateMap2", el.root, el.employees)
}

func (el *EmployeeList) getReportersById(empId int) []employee {
	reporters := []employee{}
	for _, employee := range el.employees {
		if employee.ManagerId == empId {
			reporters = append(reporters, employee)
		}
	}
	return reporters
}

func (el *EmployeeList) maketree(e *employee) {
	e.Reporters = el.getReportersById(e.Id)
	if true {
		fmt.Println("maketree", e.Id, e.Name, e.Reporters)
	}
	if len(e.Reporters) == 0 {
		return
	}
	for _, reporterEmployee := range e.Reporters {
		el.maketree(&reporterEmployee)
	}
}

func (el EmployeeList) print(root employee, level int) {
	for i := 0; i < level; i++ {
		fmt.Print("\t")
	}
	fmt.Println(root.Name)
	for _, reporter := range root.Reporters {
		el.print(reporter, level+1)
	}
}

func main() {
	//1. Read JSON File
	myJsonString := `[{"name": "Rob","id": 7,"managerid": 3},{"name": "Rex","id": 6,"managerid": 2},{"name": "Jake","id": 5,"managerid": 2},{"name": "Paul","id": 4,"managerid": 1},{"name": "Oliver","id": 3,"managerid": 1},{"name": "John","id": 2,"managerid": 1},{"name": "Britney","id": 1,"managerid": 0}]`
	//2. Create class and sent file data
	emplist := NewEmployeeList()
	rawEmployeesInfo := []employee{}

	_ = json.Unmarshal([]byte(myJsonString), &rawEmployeesInfo)
	emplist.CreateMap(rawEmployeesInfo)
	fmt.Println("Main1", emplist.root)
	emplist.maketree(&emplist.root)
	fmt.Println("Main2", emplist.root)
	emplist.print(emplist.root, 0)
}

我正在尝试从 JSON 创建一个树来存储员工列表。问题是,在创建树时,值被正确存储,但在主函数中打印层次结构树时,它们的值丢失了。请问有人可以帮我解决为什么值没有被存储的问题吗?我已经添加了日志来进行检查。

英文:
package main
import (
&quot;encoding/json&quot;
&quot;fmt&quot;
)
type employee struct {
Name      string      `json:&quot;name&quot;`
Id        int         `json:&quot;id,omitempty&quot;`
ManagerId int         `json:&quot;managerid&quot;`
Reporters []employee `json:&quot;reporters,omitempty&quot;`
}
// type employees struct {
// 	employees []employee `json:&quot;employee&quot;`
// }
type EmployeeList struct {
employees map[int]employee
root  employee
}
func NewEmployeeList() *EmployeeList {
var el EmployeeList
el.employees = make(map[int]employee)
return &amp;el
}
func (el *EmployeeList) CreateMap(employeesInfo []employee) {	 
for _ , emp := range employeesInfo {
e := employee{
Name : emp.Name,
Id: emp.Id,
ManagerId: emp.ManagerId,
}
el.employees[emp.Id] = e
if(emp.ManagerId == 0){
el.root = e
fmt.Println(&quot;CreateMap&quot;,el.root)
}
}
fmt.Println(&quot;CreateMap2&quot;,el.root,el.employees)
}
func (el *EmployeeList) getReportersById(empId int) []employee {	 
reporters := []employee{}
for _ , employee := range el.employees {
if(employee.ManagerId == empId){
reporters = append(reporters, employee)
}
}
return reporters
}
func (el *EmployeeList) maketree(e *employee) {	 
//e := root
e.Reporters = el.getReportersById(e.Id)
if(true){
fmt.Println(&quot;maketree&quot;,e.Id,e.Name,e.Reporters)
}
// e.Reporters = reporters
if(len(e.Reporters) == 0){
return
}
for _ , reporterEmployee := range e.Reporters {
el.maketree(&amp;reporterEmployee);
}
}
func (el EmployeeList) print(root employee, level int) {	 
for i:= 0; i&lt;level;i++ {
fmt.Print(&quot;\t&quot;);
}
fmt.Println(root.Name);
for _, reporter := range root.Reporters {
el.print(reporter, level + 1)
}
}
func main() {
//1. Read JSON File
myJsonString := `[{    &quot;name&quot;: &quot;Rob&quot;,    &quot;id&quot;: 7,    &quot;managerid&quot;: 3 }, {    &quot;name&quot;: &quot;Rex&quot;,    &quot;id&quot;: 6,    &quot;managerid&quot;: 2 }, {    &quot;name&quot;: &quot;Jake&quot;,    &quot;id&quot;: 5,    &quot;managerid&quot;: 2 }, {    &quot;name&quot;: &quot;Paul&quot;,    &quot;id&quot;: 4,    &quot;managerid&quot;: 1 }, {    &quot;name&quot;: &quot;Oliver&quot;,    &quot;id&quot;: 3,    &quot;managerid&quot;: 1 }, {    &quot;name&quot;: &quot;John&quot;,    &quot;id&quot;: 2,    &quot;managerid&quot;: 1 }, {    &quot;name&quot;: &quot;Britney&quot;,    &quot;id&quot;: 1,    &quot;managerid&quot;: 0 }]`
//2. Create class and sent file data
emplist := NewEmployeeList()
rawEmployeesInfo := []employee{}
_ = json.Unmarshal([]byte(myJsonString),&amp;rawEmployeesInfo);
//fmt.Println(rawEmployeesInfo);
emplist.CreateMap(rawEmployeesInfo);
//fmt.Println(emplist.employees,emplist.root);
fmt.Println(&quot;Main1&quot;,emplist.root)
emplist.maketree(&amp;emplist.root);
//fmt.Println(emplist.root)
fmt.Println(&quot;Main2&quot;,emplist.root)
emplist.print(emplist.root,0)
}

I am trying to create a tree from a json to store employee list. The problem is that while creating the tree values are stored correctly but somehow they lose value in the main function when I want to print the hierarchy tree. Can someone please help me why the value is not stored? I have added logs also to check.

答案1

得分: 3

你的CreateMap方法:

func (el EmployeeList) CreateMap(employeesInfo []employee) {
    ...
}

应该改为:

func (el *EmployeeList) CreateMap(employeesInfo []employee) {
    //---^
    ....
}

这样el就是一个指针。否则,当你执行以下操作时:

emplist.CreateMap(rawEmployeesInfo);

你实际上是在操作emplist的副本,所以你做了很多工作来创建你的映射,然后又全部丢弃了。

英文:

Your CreateMap method:

func (el EmployeeList) CreateMap(employeesInfo []employee) {
...
}

should be:

func (el *EmployeeList) CreateMap(employeesInfo []employee) {
//---^
....
}

so that el is a pointer. Otherwise you're operating on a copy of emplist when you say:

emplist.CreateMap(rawEmployeesInfo);

so you do a bunch of work to create your map and then throw it all away.

huangapple
  • 本文由 发表于 2021年12月27日 07:12:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/70490495.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定