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 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题