Introduction to Pointers
Start with Introduction to Pointers
A pointer stores the location of another variable. It lets a function or another part of a program work with the same underlying variable instead of only a copied value.
What you’ll learn
- Explain the main purpose of introduction to pointers.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
A pointer type is written with a leading asterisk: *int is a pointer to an int. The expression &score obtains the address of score, and *ptr reads the value at that address. A Go pointer does not support arbitrary pointer arithmetic.
Go still passes pointer arguments by value: the copied pointer refers to the original variable. Focus on what is shared rather than the physical address, which is not useful for a deterministic example.
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() {
score := 80
ptr := &score
fmt.Println("Score:", score)
fmt.Println("Through pointer:", *ptr)
*ptr = 95
fmt.Println("Updated score:", score)
}
Output
Score: 80
Through pointer: 80
Updated score: 95Trace what the program does
The pointer stores the address of score. Dereferencing it first reads 80; assigning 95 through the pointer changes the very same score variable, so the final print shows 95.
Avoid common mistakes
*intdeclares a pointer type, while*ptrin an expression dereferences a pointer.- Do not dereference a nil pointer.
Try it yourself
Create a variable for a temperature, take its address, then update it through a pointer. Print the original variable afterwards.
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 Introduction to Pointers 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.