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 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持