简体   繁体   中英

Runtime error “panic: assignment to entry in nil map”

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
}

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}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM