Return local pointers safely
Return local pointers safely
A Go function may return the address of a local variable. The referenced variable remains valid while it is reachable through ordinary Go pointers. Scope controls where a name can be used, not how long its storage must remain valid. No manual free is needed for an ordinary Go variable.
package main
import ( "fmt")
func makeCount(start int) *int { count := start; return &count }func main() { p := makeCount(5) *p += 2 fmt.Println(*p)}The name count is not visible in main, but its variable remains accessible through p. The compiler must preserve language behavior even when the variable outlives the function call. Do not infer the physical storage location from the return statement alone.
Expected output:
7Each call creates its own variable
package main
import ( "fmt")
func makeCount(start int) *int { count := start; return &count }func main() { a, b := makeCount(3), makeCount(3) *a = 10 fmt.Println(*a, *b, a == b)}The two calls create distinct non-zero-sized int variables. Updating a does not update b. Unreachable storage may eventually be reclaimed by the runtime, but setting one pointer to nil does not force collection or prove that no other references exist.
Expected output:
10 3 falseTry it locally
Implement makeDouble(n int) int using a local variable holding n2. Call with 4 and 7, increment the first result and print both pointed-to values.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Pointers and ownership 06: Return local pointers safely
Check the lesson objective before moving on.
Is returning &local for an ordinary local int valid Go?
What does lexical scope determine?