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 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器