March 2020
Intermediate to advanced
406 pages
8h 39m
English
The runtime.KeepAlive() function expects interface{} and ensures that the object passed to it isn't freed and that its finalizer (as defined by runtime.SetFinalizer) is not run. This keeps the argument passed to KeepAlive reachable. The compiler sets up OpKeepAlive, as defined in the static single assignment (SSA) package (https://golang.org/src/cmd/compile/internal/gc/ssa.go#L2947) – this allows the compiler to know the state of the interface as a variable and allows the keep alive context to be kept.
As a rule of thumb, we should not call KeepAlive in normal implementations. It's used to ensure that the garbage collector doesn't reclaim memory from a no longer referenced value within a function.
Read now
Unlock full access