Standard library / runtime

runtime.KeepAlive()

Ensures an object remains reachable until this call, preventing premature finalization before the last external resource use. It does not pin memory or synchronize goroutines. Expected stdout: '7\n'.

Formal Syntax & Structure

go syntaxgo
func KeepAlive(x any)

Parameters & Attributes

NameTypeDescription
xanyObject that must remain reachable through this point.

Working Example

Example Snippetgo
package main
import (  "fmt"  "runtime")
func main() { p := new(int); *p = 7; fmt.Println(*p); runtime.KeepAlive(p) }
Go Reference