How the Go Garbage Collector Works

Go uses a concurrent, non-blocking tri-color mark-and-sweep garbage collector to automatically manage memory and reclaim unused objects.

The Go garbage collector is a concurrent, non-blocking, tri-color mark-and-sweep system that automatically reclaims memory by identifying live objects and freeing unreachable ones. It runs in parallel with your program, using write barriers to track object references without stopping the world for long periods.

// The GC runs automatically; you can trigger it manually for testing:
runtime.GC()

For C interoperability (cgo), the GC cannot see C-allocated memory, so you must use runtime.SetFinalizer to free C resources when Go objects are collected. Conversely, if C code holds pointers to Go objects, you must keep a Go-side reference alive until C is done to prevent premature collection.