为了账号安全,请及时绑定邮箱和手机立即绑定

如果不存在,则映射重复键值对

如果不存在,则映射重复键值对

Go
白衣非少年 2022-05-18 09:50:13
以下是我的结构定义: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。
查看完整描述

1 回答

?
不负相思意

TA贡献1777条经验 获得超10个赞

r := make(map[string]map[string]int)只创建一个地图,它没有条目。

r1 := make(map[string]int)也只创建一个地图来计算状态,但您不需要一个,您需要为每个不同的标题创建一个单独的地图。

因此,与其创建那个单一的r1,不如按需创建内部地图。覆盖你的结构,当它的标题没有内部映射时,创建一个并将其存储在外部r映射中。

像这样:

for _, t := range ts {
    counts := r[t.Title]
    if counts == nil {
        counts = make(map[string]int)
        r[t.Title] = counts
    }
    counts[t.State]++
    }

请注意,计数操作可能只是counts[t.State]++.

有了这个输出将是(在Go Playground上尝试):

map:  map[Push 1:map[Active:2 Checked:1 InActive:1] Push 2:map[Active:1 InActive:1]]



查看完整回答
反对 回复 2022-05-18
  • 1 回答
  • 0 关注
  • 139 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号