使用xlsx包时出现恐慌:运行时错误:无效的内存地址或空指针解引用 Go

huangapple go评论96阅读模式
英文:

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
}

See a blog post about nil pointers

huangapple
  • 本文由 发表于 2017年2月10日 18:36:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/42157227.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定