drkj41932 2017-02-10 10:36
浏览 73
已采纳

使用xlsx软件包出现紧急情况:运行时错误:无效的内存地址或nil指针取消引用Go

var(    
    file            *xlsx.File
    sheet           *xlsx.Sheet
    row             *xlsx.Row
    cell            *xlsx.Cell
)

func addValue(val string) {     
        cell = row.AddCell()
        cell.Value = val
}

and imported from http://github.com/tealeg/xlsx

when ever control comes to this line

cell = row.AddCell()

It is panicking. error:

panic: runtime error: invalid memory address or nil pointer dereference

Can someone suggest whats going wrong here?

  • 写回答

1条回答 默认 最新

  • dongzhukuai8177 2017-02-10 10:59
    关注

    Nil pointer dereference

    If to attempt to read or write to address 0x0, the hardware will throw an exception that will be caught by the Go runtime and panic will be throwed. If the panic is not recovered, a stack trace is produced.

    Definitely you are trying to operate with nil value pointer.

    func addValue(val string) {
        var row *xlsx.Row // nil value pointer
        var cell *xlsx.Cell
        cell = row.AddCell() // Attempt to add Cell to address 0x0.
        cell.Value = val
    }
    

    Allocate memory first

    func new(Type) *Type:

    It's a built-in function that allocates memory, but unlike its namesakes in some other languages it does not initialize the memory, it only zeros it. That is, new(T) allocates zeroed storage for a new item of type T and returns its address, a value of type *T. In Go terminology, it returns a pointer to a newly allocated zero value of type T.

    Use new function instead of nil pointers:

    func addValue(val string) {
        row := new(xlsx.Row)
        cell := new(xlsx.Cell)
        cell = row.AddCell()
        cell.Value = val
    }
    

    See a blog post about nil pointers

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

报告相同问题?

悬赏问题

  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 前端echarts坐标轴问题
  • ¥15 CMFCPropertyPage
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题
  • ¥15 谁会P4语言啊,我想请教一下
  • ¥15 这个怎么改成直流激励源给加热电阻提供5a电流呀
  • ¥50 求解vmware的网络模式问题 别拿AI回答