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

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

报告相同问题?