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 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)