Compare ownership and memory trade-offs
Compare ownership and memory trade-offs
Data structures differ in allocation, locality and sharing. A slice often stores adjacent elements in one backing array; linked nodes may require separate allocations and pointer chasing. Copying a slice descriptor shares the backing array, while cloning its elements creates separate slice storage. Go garbage collection does not enforce exclusive ownership.
package main
import ( "fmt" "slices")
func main() { a := []int{1, 2, 3} view := a[:2] clone := slices.Clone(view) view[0] = 9 clone[1] = 7 fmt.Println(a, view, clone)}The view aliases a; the clone has separate storage for these integers. Cloning is shallow: if elements contain pointers, maps or slices, their referenced data can still be shared. APIs should say whether they return a view, a snapshot or transfer responsibility for mutation.
Expected output:
[9 2 3] [9 2] [1 7]Remove references from a queue
package main
import ( "fmt")
func take(q []*int) ([]*int, *int, bool) { if len(q) == 0 { return q, nil, false } v := q[0] q[0] = nil return q[1:], v, true}func main() { a, b := 1, 2 q := []*int{&a, &b} original := q rest, v, ok := take(q) fmt.Println(*v, ok, original[0] == nil, *rest[0]) _, _, ok = take(nil) fmt.Println(ok)}Clearing the consumed slot prevents that slot from retaining the object; it also changes any aliases to the same array. The remaining slice may still retain the original backing allocation. Other references may keep the object alive, so GC timing is not guaranteed. Use a ring buffer for fixed capacity or periodically copy live entries if measurement shows retention is a problem. Do not claim a memory or speed advantage without measuring a representative workload.
Expected output:
1 true true 2falseTry it locally
Implement a snapshot function that copies a []int with slices.Clone. Change the original after taking a snapshot and print both to demonstrate independence.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Data structures 08: Compare ownership and memory trade-offs
Check the lesson objective before moving on.
Does cloning a slice of pointers clone the objects they point to?
What does clearing a removed pointer slot guarantee?