Skip to content

Golang: When a Variable Can Be nil? (invalid memory address)

There are two concepts to learn: empty and nil. Some variables can be nil, for example, a pointer can be nil and if you do not check it before using it, boom!

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

Take a look at this example, this will help you learn when a variable can be nil:

package main

import "fmt"

type Website struct {
	Url   string
	Title string
}

func main() {

	// structs can not be nil
	emptyStruct := Website{}

	fmt.Printf("type:%T value:%v \n", emptyStruct, emptyStruct)

	// pointers can be nil, it is not point to an address yet then it is nil
	var nilPointer *Website

	fmt.Printf("type:%T value:%v \n", nilPointer, nilPointer)

	// now it is pointing to a struct, then it is not nil anymore
	nilPointer = &emptyStruct

	fmt.Printf("type:%T value:%v \n", nilPointer, nilPointer)
}

How to fix it problem? Just check if the variable is empty or not by == operator:

package main

import "fmt"

func main() {

	var myPointer *string

	if myPointer == nil {
		fmt.Println("I am nil.")
		// decide what you want to do
	}
}

Leave a Reply

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