duan02143 2015-09-18 05:09
浏览 102
已采纳

界面的golang映射-恐慌:在nil映射中分配给条目[重复]

This question already has an answer here:

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)
}
</div>
  • 写回答

1条回答 默认 最新

  • doujiao7325 2015-09-18 05:12
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 镍氢电池充电器设计实物使用原理
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号