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

以下是我的结构定义:


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。


白衣非少年
浏览 140回答 1
1回答

不负相思意

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]]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go