dqroc48068 2017-12-01 20:47
浏览 125
已采纳

什么是无效的内存地址或Golang中的nil指针取消引用,如何解决? [关闭]

I am getting the following error:

panic: runtime error: invalid memory address or nil pointer dereference [signal 0xb code=0x1 addr=0x0 pc=0x400da9]

goroutine 125 [running]: runtime.panic(0x697480, 0x850d13) /usr/lib/go/src/pkg/runtime/panic.c:279 +0xf5 main.concurrent(0x25e5) /home/ytn/go/src/listner/start.go:19 +0x1a9 created by main.main /home/ytn/go/src/listner/init.go:51 +0x224

How can I fix it and What is the best practice to avoid this kind of error?

   for i := n; i < n+11; i++ {
            user,  err := s.GetUser(i)
            fmt.Sprint(user.Username) //This is line 19
            if err != nil && user != nil {
              continue
           }
     } defer wg.Done()
  • 写回答

1条回答 默认 最新

  • dongyao2022 2017-12-01 20:51
    关注

    It's hard to say how to fix it without seeing your code, but basically it means you have a pointer that is nil, and you are trying to get the value that it points to:

    var x *MyStruct
    fmt.Println(*x)
    

    to fix it, you would need to either check if it's nil before dereferencing it:

    var x *MyStruct
    if x != nil {
        fmt.Println(*x)
    }
    

    or get it to actually point to a value

    var x *int
    x = &MyStruct{}
    fmt.Println(*x)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误