[Go] Solve panic: runtime error: invalid memory address or nil pointer dereference in golang

When a property or method is called on nil, a null pointer will be reported

Especially the structure pointer, this problem is very easy to occur, the following is the test code

package tools

import "fmt"

func MyTest() {
    type MConn struct {
        Name string
    }
    var conn * MConn
    var conn2 MConn
    conn3 := new (MConn)
    conn4 := & MConn{}
    fmt.Printf("%v,%v,%v,%v" , conn, conn2, conn3, conn4)
}

Return separately

<nil>,{},&{},&{}

When a structure pointer variable var conn *MConn is declared, but it is not initialized and the property is called directly, it will appear

panic: runtime error: invalid memory address or nil pointer dereference

Because conn is nil at this time, it is a null pointer

A null operation must be performed, if conn != nil {}

 

Of course, we sometimes do not make such an obvious error, but when we cooperate with map, this error may occur unintentionally.

    var mMap map[ string ]* MConn
    m1: = mMap[ " name " ]
    m1.Name = " qqq "

In this code map, when the key element does not exist, the zero value of value is returned, which happens to be *MConn. The zero value is nil, and an error will also be reported.

So the map has to be judged here

    var mMap map[ string ]* MConn
    m1, ok: = mMap[ " name " ]
     if ok {
        m1.Name = " qqq " 
    }


Read More:

Leave a Reply

Your email address will not be published. Required fields are marked *