以下是我的结构定义:
type test struct{
Title string
State string
Counts int
}
我想以下列方式映射结构对象成员 map[Title:map[State:Counts]]
这是成功执行此操作的代码
func main() {
r := make(map[string]map[string]int)
r1 := make(map[string]int)
var ts []test
ts = append(ts, test{Title: "Push 1",
State: "Active",
Counts: 20})
ts = append(ts, test{Title: "Push 1",
State: "InActive",
Counts: 20})
ts = append(ts, test{Title: "Push 1",
State: "Checked",
Counts: 20})
ts = append(ts, test{Title: "Push 1",
State: "Active",
Counts: 23})
ts = append(ts, test{Title: "Push 2",
State: "Active",
Counts: 20})
ts = append(ts, test{Title: "Push 2",
State: "InActive",
Counts: 23})
for _, t := range ts {
r1[t.State] = t.Counts
r[t.Title] = r1
}
fmt.Println("struct: ", ts)
fmt.Println("map: ", r)
}
我面临的问题是标题“Push 2”没有State: Checked附加上一个对象的计数值。以下输出如下
struct: [{Push 1 Active 20} {Push 1 InActive 20} {Push 1 Checked 20} {Push 1 Active 23} {Push 2 Active 20} {Push 2 InActive 23}]
map: map[Push 1:map[Active:20 Checked:20 InActive:23] Push 2:map[Active:20 Checked:20 InActive:23]]
我编译的代码在 go playground。
不负相思意
相关分类