【问题标题】:Using xlsx package panic: runtime error: invalid memory address or nil pointer dereference Go使用 xlsx 包 panic: runtime error: invalid memory address or nil pointer dereference Go
【发布时间】:2017-06-28 16:11:06
【问题描述】:
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()

这是恐慌。 错误:

恐慌:运行时错误:无效的内存地址或 nil 指针取消引用

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

【问题讨论】:

    标签: pointers go dereference panic


    【解决方案1】:

    Nil 指针解引用

    如果尝试读取或写入地址 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:

    它是一个分配内存的内置函数,但与其他一些语言中的同名函数不同,它不会初始化内存,它只会将它归零。也就是说,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
    }
    

    See a blog post about nil pointers

    【讨论】:

    • 我已经在 var 中声明了它(文件 *xlsx.File sheet *xlsx.Sheet row *xlsx.Row cell *xlsx.Cell )
    • @gophervk,nil 指针的声明不是你需要的。请仔细阅读我的帖子和我提到的博客。
    • @gophervk,删除那个 html 包装器。现在格式不正确。
    • l159,我可以用 new 写,但在这里它不会把东西写到声明的公共文件中
    • @l159,我没有看到任何 html 包装器。我清除并更新了一个输入错误
    猜你喜欢
    • 1970-01-01
    • 2018-02-07
    • 2017-04-28
    • 1970-01-01
    • 2015-11-19
    • 1970-01-01
    • 2021-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多