Understanding Go Memory Management
Start with Understanding Go Memory Management
Go manages memory automatically, but a programmer still decides which data is shared, retained and copied.
What you’ll learn
- Explain the main purpose of understanding go memory management.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
The compiler’s escape analysis helps decide whether values may live in stack frames or require longer-lived storage; source-level use of new or & does not by itself determine heap allocation. Avoid relying on a particular physical allocation location.
Large backing arrays can stay alive while a tiny slice refers to them. Copying only the data needed into a new slice can allow an otherwise unused large backing array to become collectible. The example uses a small slice to illustrate the ownership difference.
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() {
original := []int{10, 20, 30, 40}
view := original[1:3]
independent := append([]int(nil), view...)
view[0] = 99
fmt.Println("Original:", original)
fmt.Println("View:", view)
fmt.Println("Copy:", independent)
}
Output
Original: [10 99 30 40]
View: [99 30]
Copy: [20 30]Trace what the program does
view and original share the same backing array, so changing view[0] changes original[1]. The independent slice contains a copy of the values from before that change and remains [20 30].
Avoid common mistakes
- Memory visibility and lifetime are not equivalent to a guaranteed stack-versus-heap location.
- A small subslice may keep a much larger backing array reachable.
Try it yourself
Use copy instead of append to produce an independent slice. Change the source and check that the copy is unchanged.
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 Understanding Go Memory Management 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.