Pointer Declaration
Start with Pointer Declaration
A pointer variable has its own type, such as *int or *string. An uninitialized pointer holds nil until you assign a valid address or allocate an object.
What you’ll learn
- Explain the main purpose of pointer declaration.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
Write var p *int to declare a pointer capable of referring to an integer. Initially, p == nil is true. Assign p = &number to make it refer to an existing integer variable.
Pointer types matter: a *string cannot be assigned to a *int. Use explicit types to make the intended target clear, especially when declaring structures and function parameters.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import "fmt"
func main() {
var p *int
fmt.Println("Initially nil:", p == nil)
number := 42
p = &number
fmt.Println("After assignment:", p == nil)
fmt.Println("Value:", *p)
}
Output
Initially nil: true
After assignment: false
Value: 42Trace what the program does
The declared pointer starts as nil; after p is assigned the address of number, it becomes non-nil and its dereferenced value is 42.
Avoid common mistakes
- A pointer declaration does not create a target integer.
- Do not use
*pbefore a non-nil target has been assigned.
Try it yourself
Declare var text *string, assign the address of a string variable, and print it using *text.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Pointer Declaration in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.