Using xlsx package panic: runtime error: invalid memory address or nil pointer dereference Go

Using xlsx package panic: runtime error: invalid memory address or nil pointer dereference Go

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

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

并从 http://github.com/tealeg/xlsx

导入

当控制权到达此行时

cell = row.AddCell()

很恐慌。 错误:

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

有人能指出这里出了什么问题吗?

零指针取消引用

如果尝试读取或写入地址 0x0,硬件将抛出异常,Go 运行时将捕获该异常并抛出恐慌。如果恐慌未恢复,则会生成堆栈跟踪。

您肯定在尝试使用 nil 值指针进行操作。

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
}

先分配内存

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.

使用new函数代替空指针:

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