Go nil pointer check
A nil pointer can represent an absent optional phone number.
A simple example
nil pointer check
- Start with No string supplied
- Do this Try to read its length
- Result No length available
Syntax
phone == nil
Run these examples in Go
Save one example at a time as main.go. Use Go 1.21 or later.
go run main.goPrint a label when the phone number is missing
A school prints contact cards from an enrollment form. Some families leave the optional phone field blank, so the printer needs a readable fallback before it measures or displays that field.
package main
import (
"fmt"
)
func main() {
var phone *string
if phone == nil {
fmt.Println("Ask for a phone number")
} else {
fmt.Println(*phone)
}
}
Ask for a phone number
The missing contact follows the fallback branch, so the card still has a printable phone field.
Print an existing extension
A department saved its internal extension in the staff directory. Confirm that a contact value is available before printing it on a dispatch slip.
Flag an unfilled contact field
A delivery booking reaches reception without a contact value. Confirm that a contact value is available before printing it on a dispatch slip.
What to watch for
Dereferencing a nil pointer panics. Treat the missing value as an expected branch at the form boundary.