dtnqbre7980007 2018-06-03 16:58
浏览 54
已采纳

运行时错误“紧急:在nil映射中分配给条目”

i made a config.go which helps to edit a config file but i've got a bug with map being nil and this is where the error is suposed to come from:

type(
    Content map[string]interface{}
    Config struct {
         file       string
         config     Content
         configType int
    }
)
func (c *Config) Set(key string, value interface{}) {
    c.config[key] = value
}
  • 写回答

1条回答 默认 最新

  • dongranding3909 2018-06-03 17:41
    关注

    The Go Programming Language Specification

    Map types

    A map is an unordered group of elements of one type, called the element type, indexed by a set of unique keys of another type, called the key type. The value of an uninitialized map is nil.

    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.


    The value of an uninitialized map is nil. Initialize the map before the first write.

    For example,

    package main
    
    import (
        "fmt"
    )
    
    type (
        Content map[string]interface{}
        Config  struct {
            file       string
            config     Content
            configType int
        }
    )
    
    func (c *Config) Set(key string, value interface{}) {
        if c.config == nil {
            c.config = make(Content)
        }
        c.config[key] = value
    }
    
    func main() {
        var c Config
        c.Set("keya", "valuea")
        fmt.Println(c)
        c.Set("keyb", "valueb")
        fmt.Println(c)
    }
    

    Playground: https://play.golang.org/p/6AnvIZZRml_y

    Output:

    { map[keya:valuea] 0}
    { map[keya:valuea keyb:valueb] 0}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 如何将下列的“无限压缩存储器”设计出来
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口