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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵