doumeilmikv7099 2016-01-24 04:16
浏览 44
已采纳

嵌套地图golang的结构

Hi I'm new to go and was trying to figure out how maps work. I have made up a little test program and can't seem to get it to work. What I'm doing wrong?

package main

import (
    "fmt"
)

type Stats struct {
    cnt      int
    category map[string]Events
}

type Events struct {
    cnt   int
    event map[string]Event
}

type Event struct {
    value int64
}

func main() {

    stats := new(Stats)
    stats.cnt = 33
    stats.category["aa"].cnt = 66
    stats.category["aa"].event["bb"].value = 99

    fmt.Println(stats.cnt, stats.category["aa"].event["bb"].value)
}
  • 写回答

3条回答 默认 最新

  • dongxie1907 2016-01-24 05:07
    关注

    There are couple of issues with the code:

    1. Map needs to be initialized using make function. Currently they are nil

    2. Return value from map is non-addressable, this because if map is growing it needs to relocated which will cause memory address to change. Hence we need to extract value explicitly from map to a variable, update it and assigning it back.

    3. Use pointer

    I have updated the solution to show both updated it value returned and assigning it back and pointer.

    http://play.golang.org/p/lv50AONXyU

    package main
    
    import (
        "fmt"
    )
    
    type Stats struct {
        cnt      int
        category map[string]Events
    }
    
    type Events struct {
        cnt   int
        event map[string]*Event
    }
    
    type Event struct {
        value int64
    }
    
    func main() {
    
        stats := new(Stats)
        stats.cnt = 33
        stats.category = make(map[string]Events)
        e, f := stats.category["aa"]
        if !f {
            e = Events{}
        }
        e.cnt = 66
    
        e.event = make(map[string]*Event)
        stats.category["aa"] = e
        stats.category["aa"].event["bb"] = &Event{}
        stats.category["aa"].event["bb"].value = 99
    
        fmt.Println(stats)
        fmt.Println(stats.cnt, stats.category["aa"].event["bb"].value)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 打开软件提示错误:failed to get wglChoosePixelFormatARB
  • ¥30 电脑误删了手机的照片怎么恢复?
  • ¥15 (标签-python|关键词-char)
  • ¥15 python+selenium,在新增时弹出了一个输入框
  • ¥15 苹果验机结果的api接口哪里有??单次调用1毛钱及以下。
  • ¥20 学生成绩管理系统设计
  • ¥15 来一个cc穿盾脚本开发者
  • ¥15 CST2023安装报错
  • ¥15 使用diffusionbert生成文字 结果是PAD和UNK怎么办
  • ¥15 有人懂怎么做大模型的客服系统吗?卡住了卡住了