Nil Pointers
Part of the Fundamentals section of Coddy's GO journey — lesson 65 of 109.
A nil pointer is a pointer that doesn't point to anything. It's the zero value for pointer types.
Declare a nil pointer:
var ptr *int
fmt.Println(ptr)
fmt.Println(ptr == nil)The output shows the pointer is nil:
<nil>
trueAttempting to dereference a nil pointer causes a panic:
var ptr *int
// This will crash your program
// fmt.Println(*ptr)Always check if a pointer is nil before dereferencing:
if ptr != nil {
fmt.Println(*ptr)
}Challenge
BeginnerIn this challenge, you'll work with nil pointers in Go. A nil pointer is a pointer that doesn't point to any memory address.
Your task is to check if a pointer is nil and print an appropriate message.
The code already has a pointer variable that is set to nil. You need to add code to check if the pointer is nil and print a message accordingly.
Cheat sheet
A nil pointer is a pointer that doesn't point to anything. It's the zero value for pointer types.
Declare a nil pointer:
var ptr *int
fmt.Println(ptr) // <nil>
fmt.Println(ptr == nil) // trueAlways check if a pointer is nil before dereferencing to avoid panics:
if ptr != nil {
fmt.Println(*ptr)
}Try it yourself
package main
import "fmt"
func main() {
// This is a nil pointer to an integer
var ptr *int
// TODO: Check if ptr is nil
// If it is nil, print "The pointer is nil"
// If it is not nil, print "The pointer is not nil"
fmt.Println("Program completed")
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Comparison & Logical Operators
Comparison Operators - Part 1Comparison Operators - Part 2Logical AND OperatorLogical OR OperatorLogical NOT OperatorOperator Precedence BasicsRecap - Making Comparisons7Control Flow: Loops
What The `for` Loop ExplainedFor Loop - BasicFor Loop - Condition OnlyThe `break` KeywordThe `continue` KeywordNested LoopsRecap - Repeating Actions2Variables and Basic Data Types
What is a variableType Inference with `:=`Integers (int)Floating-Point NumbersBooleansStringsZero ValuesConstantsNaming ConventionsRecap - Variables and Types5Basic Input/Output
Formatted OutputFormat VerbsPrinting TypesGetting Basic User InputRecap - Input and Output8Functions
Understanding FunctionsDeclaring a FunctionCalling FunctionsFunction ParametersReturning a Single ValueReturning Multiple ValuesNamed Return ValuesFunction Scope BasicsRecap - Creating Reusable Code3Basic Operators
Arithmetic OperatorsDivision OperatorThe Modulo OperatorAssignment OperatorAugmented Assignment OperatorsIncrement and DecrementRecap - Calculations6Control Flow: Conditionals
The `if` StatementThe `else` KeywordThe `else if` KeywordVariable Shadowing in `if`Initializing VariablesThe `switch` StatementSwitch with ExpressionsSwitch without ExpressionThe `fallthrough` KeywordRecap - Making Decisions