Ad space (banner)
๐ŸนGo Lessons
Lesson 21 / 68

Writing nil-Safe Code (Checking a Pointer for nil)

In this lesson you will learn to handle values safely against nil in Go, avoiding errors when a value has not been set. This is for anyone searching for "Go nil handling".

Go uses nil to represent the absence of a value (for pointers, slices, maps, and more). Checking with == nil before use is the basic discipline.

The sample code checks whether the pointer declared as var address *string is nil using if address == nil, printing "No address set" when there is no value. Dereferencing a nil pointer crashes the program, so this check is a habit in real Go code.

A common stumbling block for beginners is dereferencing without checking, as in *address. That is one of the classic causes of a runtime panic. It is also characteristically Go that reading from a nil slice or map is usually safe and simply behaves as empty.

In real-world development, allowing for values from a database or an API being empty, and writing nil-safe code to head off errors, is taken seriously.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Go directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)