golang中的map接口 – panic: 将值分配给空map的条目

huangapple go评论150阅读模式
英文:

golang map of interface - panic: assignment to entry in nil map

问题

我是你的中文翻译助手,以下是你要翻译的内容:

我是golang的新手,我正在尝试创建一个类型为map[string]interface{}的映射。

但是当我尝试在键不存在时创建一个新键时,我会得到一个运行时错误"panic: assignment to entry in nil map"。有人可以告诉我我做错了什么吗?

Go PlayGround: https://play.golang.org/p/vIEE0T11yl

这是我的代码:

package main

func main() {
    buffer := Buffer{}
    buffer.AddRecord("myKey", 12345)
}

type Buffer struct {
    records    map[string][]interface{}
}

// ProcessRecord将一条消息添加到缓冲区。
func (buffer *Buffer) AddRecord(key string, record interface{}) {
    _, ok := buffer.records[key]
    if !ok {
        buffer.records[key] = make([]interface{}, 0)
    }

    buffer.records[key] = append(buffer.records[key], record)
}
英文:

I am new to golang and I am trying to create a map of type map[string]interface{}.

But when I try to create a new key when it doesn't exists, I get a runtime error "panic: assignment to entry in nil map". Can anyone tell me what I am doing wrong please?

Go PlayGround: https://play.golang.org/p/vIEE0T11yl

Here is my code:

package main

func main() {
	buffer := Buffer{}
	buffer.AddRecord("myKey", 12345)
}

type Buffer struct {
	records    map[string][]interface{}
}

// ProcessRecord adds a message to the buffer.
func (buffer *Buffer) AddRecord(key string, record interface{}) {
	_, ok := buffer.records[key]
	if !ok {
		buffer.records[key] = make([]interface{}, 0)
	}

	buffer.records[key] = append(buffer.records[key], record)
}

答案1

得分: 11

你需要初始化地图本身:https://play.golang.org/p/wl4mMGjmRP

func (buffer *Buffer) AddRecord(key string, record interface{}) {
    // 检查是否为nil,否则初始化地图
    if buffer.records == nil {
        buffer.records = make(map[string][]interface{})
    }
    _, ok := buffer.records[key]
    if !ok {
        buffer.records[key] = make([]interface{}, 0)
    }

    buffer.records[key] = append(buffer.records[key], record)
}

你也可以为你的结构体类型使用一个构造函数 - 例如 NewBuffer(...) *Buffer - 它也会初始化字段,但在使用之前检查是否为nil是一个好的做法。对于访问地图键也是一样的。

英文:

You need to initialise the map itself: https://play.golang.org/p/wl4mMGjmRP

func (buffer *Buffer) AddRecord(key string, record interface{}) {
    // Check for nil, else initialise the map
    if buffer.records == nil {
        buffer.records = make(map[string][]interface{})
    }
	_, ok := buffer.records[key]
	if !ok {
		buffer.records[key] = make([]interface{}, 0)
	}

	buffer.records[key] = append(buffer.records[key], record)
}

You could also use a constructor for your struct type - e.g. NewBuffer(...) *Buffer - that initialises the field as well, but it's good practice to check for nil before using it. Same goes for accessing map keys.

huangapple
  • 本文由 发表于 2015年9月18日 13:09:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/32644293.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定