【问题标题】:Runtime error "panic: assignment to entry in nil map"运行时错误“恐慌:分配给零映射中的条目”
【发布时间】:2018-06-03 16:58:00
【问题描述】:

我制作了一个 config.go,它有助于编辑配置文件,但我遇到了一个错误,地图为 nil,这就是错误的来源:

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
}

【问题讨论】:

  • 但是我会丢失旧的内容

标签: go


【解决方案1】:

The Go Programming Language Specification

Map types

地图是一种类型的无序元素组,称为 元素类型,由一组另一种类型的唯一键索引,称为 密钥类型。未初始化的map的值为nil。

使用内置函数 make 生成一个新的空映射值,该函数 将地图类型和可选容量提示作为参数:

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

初始容量不限制其大小:地图会增长以适应 存储在其中的项目数,nil 地图除外。一个 nil map 等价于一个空 map,除了没有元素可以是 已添加。


未初始化映射的值为nil。在第一次写入之前初始化映射。

例如,

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)
}

游乐场:https://play.golang.org/p/6AnvIZZRml_y

输出:

{ map[keya:valuea] 0}
{ map[keya:valuea keyb:valueb] 0}

【讨论】:

  • 另外,对于像这样的类型,提供一个新的函数来设置它们有用的起始值可能是有用的
猜你喜欢
  • 1970-01-01
  • 2015-01-31
  • 2013-02-13
  • 2020-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-13
  • 1970-01-01
相关资源
最近更新 更多