Understand unsafe.Pointer and uintptr lifetime
Understand unsafe.Pointer and uintptr lifetime
unsafe.Pointer permits conversions ordinary pointers do not. uintptr is an unsigned integer large enough to hold pointer bits, not a reference that keeps an object alive. Prefer typed pointers. Unsafe code must obey documented conversion and lifetime rules even if a test works.
package main
import ( "fmt" "runtime" "unsafe")
func main() { n := 19 p := unsafe.Pointer(&n) q := (*int)(p) fmt.Println(*q, q == &n) runtime.KeepAlive(&n)}This converts a pointer to unsafe.Pointer and back to the same type. The object stays referenced. Converting to uintptr discards pointer semantics: the collector does not track it as a reference or update it if the object moves. Do not store an address as uintptr and reconstruct a pointer later. KeepAlive cannot legalize an invalid conversion.
Expected output:
19 trueUse typed pointers instead
package main
import ( "fmt")
func main() { a := [2]int{8, 9} p := &a[1] *p = 10 fmt.Println(a)}Ordinary indexing preserves bounds checks and type safety. Consult the unsafe.Pointer documentation for the limited permitted patterns. Vet and checkptr are supplementary diagnostics, not proofs of correctness. Unsafe code may be nonportable and is not protected by the Go 1 compatibility promise.
Expected output:
[8 10]Try it locally
Modify the first element of [3, 5] to 4 using a typed pointer, without unsafe.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Reflection and unsafe 06: Understand unsafe.Pointer and uintptr lifetime
Check the lesson objective before moving on.
Does uintptr keep the referenced object alive?
What is preferred for updating an array element?