package mainimport ( "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 employees struct {// employees []employee `json:"employee"`// }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 := root e.Reporters = el.getReportersById(e.Id) if(true){ fmt.Println("maketree",e.Id,e.Name,e.Reporters) } // e.Reporters = reporters if(len(e.Reporters) == 0){ return } for _ , reporterEmployee := range e.Reporters { el.maketree(&reporterEmployee); }}我正在嘗試從 json 創(chuàng)建一棵樹來(lái)存儲(chǔ)員工列表。問題是,雖然創(chuàng)建樹的值被正確存儲(chǔ),但是當(dāng)我想打印層次結(jié)構(gòu)樹時(shí),它們?cè)谥骱瘮?shù)中失去了價(jià)值。有人可以幫我為什么不存儲(chǔ)價(jià)值嗎?我還添加了日志以進(jìn)行檢查。
1 回答

jeck貓
TA貢獻(xiàn)1909條經(jīng)驗(yàn) 獲得超7個(gè)贊
你的CreateMap方法:
func (el EmployeeList) CreateMap(employeesInfo []employee) {
...
}
應(yīng)該:
func (el *EmployeeList) CreateMap(employeesInfo []employee) {
//---^
....
}
所以這el是一個(gè)指針。否則,emplist當(dāng)您說(shuō):
emplist.CreateMap(rawEmployeesInfo);
所以你做了很多工作來(lái)創(chuàng)建你的地圖,然后把它扔掉。
- 1 回答
- 0 關(guān)注
- 138 瀏覽
添加回答
舉報(bào)
0/150
提交
取消