英文:
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: 运行时错误:无效的内存地址或空指针解引用
有人能够建议一下这里出了什么问题吗?
英文:
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
得分: 0
空指针解引用
如果尝试读取或写入地址0x0,硬件将抛出一个异常,该异常将被Go运行时捕获,并引发panic。如果未恢复panic,将生成堆栈跟踪。
显然,您正在尝试操作空值指针。
func addValue(val string) {
var row *xlsx.Row // 空值指针
var cell *xlsx.Cell
cell = row.AddCell() // 尝试将Cell添加到地址0x0。
cell.Value = val
}
先分配内存
func new(Type) *Type
:
> 这是一个内置函数,用于分配内存,但与其他一些语言中的同名函数不同,它不会初始化内存,只会将其清零。也就是说,new(T)为类型为T的新项目分配了一个零值的存储空间,并返回其地址,即类型为*T的值。在Go术语中,它返回一个指向新分配的类型T的零值的指针。
使用new
函数而不是空指针:
func addValue(val string) {
row := new(xlsx.Row)
cell := new(xlsx.Cell)
cell = row.AddCell()
cell.Value = val
}
英文:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论