What is invalid memory address or nil pointer dereference in Golang, How can I fix it?

go
21,716

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 *MyStruct
x = &MyStruct{}
fmt.Println(*x)
Share:
21,716

Related videos on Youtube

ybnsl
Author by

ybnsl

Updated on September 01, 2020

Comments

  • ybnsl
    ybnsl over 3 years

    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()
    
    • Andy Schweig
      Andy Schweig over 6 years
      You're most likely using a nil pointer. Look at what that line of code is doing and it should be clear.
    • Adrian
      Adrian over 6 years
      Without the relevant code included, no one can offer much help. "nil pointer dereference" means you're trying to access a pointer whose value is nil. Best practice to avoid it is not to do that.