pointers - 使用 xlsx 包 panic : runtime error: invalid memory address or nil pointer dereference Go

标签 pointers go dereference panic

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 。 错误:

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

有人可以建议这里出了什么问题吗?

最佳答案

零指针解引用

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

您肯定在尝试使用 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) *类型:

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 函数代替 nil 指针:

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

关于pointers - 使用 xlsx 包 panic : runtime error: invalid memory address or nil pointer dereference Go,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42157227/

相关文章:

c - 使用 C 打印指向字符串的指针数组,省略最后一个字符串

c - 在 32 位模式下使用 64 位 uint 作为指针值?

PHP 解引用数组元素

java - 从 String[] 的 ArrayList 打印一个字符串?

c++ - 在 C++ vector 中使用取消引用运算符

C结构问题

c - 为什么FILE指针无法读取文件中的内容?

go - 无法理解去价套餐

mysql - 其他情况似乎无法正常工作

Go 编译已声明但未使用