dongzhi6146 2016-02-13 11:40 采纳率: 100%
浏览 131
已采纳

Go:分配给nil映射中的条目

I'm rather new in go, and I searched for this trouble on this site, and founed answered questions, but cannot implement those answers to my case. I have a code :

func receiveWork(out <-chan Work) map[string][]ChartElement {

    var countedData map[string][]ChartElement

    for el := range out {
        countedData[el.Name] = el.Data
    }
    fmt.Println("This is never executed !!!")

    return countedData
}

there are no troubles with structs outside this method. Also Println not executes(as test that panic is here). I understands that the trouble is in incrementing data to the structure.

There are some goroutines , that are sending data to channel, and receiveWork method rgabs it all and should make a map like this:

map =>
    "typeOne" => 
       [
         ChartElement,
         ChartElement,
         ChartElement,
       ],
    "typeTwo" => 
       [
         ChartElement,
         ChartElement,
         ChartElement,
       ]

How to realize this inserting in a proper way?

  • 写回答

1条回答 默认 最新

  • dongpu2476 2016-02-13 12:36
    关注

    The Go Programming Language Specification

    Map types

    A new, empty map value is made using the built-in function make, which takes the map type and an optional capacity hint as arguments:

    make(map[string]int)
    make(map[string]int, 100)
    

    The initial capacity does not bound its size: maps grow to accommodate the number of items stored in them, with the exception of nil maps. A nil map is equivalent to an empty map except that no elements may be added.

    You write:

    var countedData map[string][]ChartElement
    

    Instead, to initialize the map, write,

    countedData := make(map[string][]ChartElement)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度