```
// Region2 for map-id
type Region2 struct {
ID int64
ParentID int64
Name string
Children map[int64]*Region2
}
var rm = map[int64]*tables.Region{}
var r2m = map[int64]*Region2{}
err := engine.Find(&rm, 0, 0)
if err != nil {
return r2m, err
}
for _, r := range rm {
r2m[r.ID] = &Region2{
ID: r.ID,
ParentID: r.ParentID,
Name: r.Name,
Children: make(map[int64]*Region2),
}
nr := *r
for nr.ParentID != 0 {
QUESTION:
_, ok := r2m[nr.ParentID] -----------------------------------------1
if !ok { ------------------------------------------1
if _, ok := r2m[nr.ParentID] ;!ok{ ------------------------------------------2
r2m[nr.ParentID] = &Region2{
ID: rm[nr.ParentID].ID,
ParentID: rm[nr.ParentID].ParentID,
Name: rm[nr.ParentID].Name,
Children: make(map[int64]*Region2),
}
}
r2m[nr.ParentID].Children[nr.ID] = r2m[nr.ID]
nr = *rm[nr.ParentID]
}
}
```
### 测试数据
|id|parent_id| name |
|:----|:----:|-----|
|923852550304698368|0| 测试有一级区域1|
|923852550304698369|923852550304698368|一级子区域1|
### 描述
以上问一段代码源码,我的意图是构造一个 `region 树`,目标结果是 r2m:map[923852550304698368:0xc422360870 923852550304698369:0xc4223608d0] ,r2m[923852550304698368]:&{923852550304698368 0 测试有一级区域1 map[923852550304698369:0xc4223608d0]}
在标记 `QUESTION` 段,如采用 1 写法,基本没问题,但是采用2写法时候,有概率出现 r2m[923852550304698368]:&{923852550304698368 0 测试有一级区域1 map[]} 的情况,请问是怎么回事?
有疑问加站长微信联系(非本文作者)