gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 03:25:50 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com