Trace aliasing and ownership
Trace aliasing and ownership
Aliasing occurs when multiple pointers refer to the same variable. A write through one pointer is visible when reading through another. Go does not enforce exclusive ownership or move semantics for ordinary pointers; ownership here means the application’s convention about who may mutate shared data.
package main
import ( "fmt")
func main() { balance := 20 p := &balance q := p *q += 5 fmt.Println(*p, balance) q = nil fmt.Println(*p, q == nil)}Copying p into q shares the referenced variable. Setting q to nil does not change p or balance. The pointer variables themselves are separate. Shared mutable state requires an explicit mutation contract; simultaneous unsynchronized access with a write can be a data race.
Expected output:
25 2525 trueCopy the value instead
package main
import ( "fmt")
func cloneInt(p *int) *int { if p == nil { return nil } v := *p return &v}func main() { x := 4 p := &x q := cloneInt(p) *q = 9 fmt.Println(*p, *q, p == q) fmt.Println(cloneInt(nil) == nil)}The function creates a distinct integer variable, preserving absence for nil. Copying an int is sufficient here. For a slice, map or composite containing pointers, copying the top-level value may still share underlying data. Returning a local address is safe, as the next lesson explains.
Expected output:
4 9 falsetrueTry it locally
Create n=6 and pointers p and q to it. Set *q to 8. Copy *p into independent variable copyValue and change copyValue to 12. Print n, *q and copyValue.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Pointers and ownership 05: Trace aliasing and ownership
Check the lesson objective before moving on.
What does q := p copy when p is *int?
How can you make a separate int from non-nil p?