Sobes.tech
Senior

What is a garbage collector in Go?

sobes.tech AI

Answer from AI

Garbage collector (GC) in Go is an automatic memory management mechanism that frees unused objects to prevent memory leaks. Go uses a concurrent, trigger-based low-latency garbage collector that runs in parallel with the main execution thread.

GC in Go tracks objects that are no longer referenced and frees the memory they occupy. This allows developers not to worry about manual memory management, reducing the likelihood of errors such as double freeing or leaks.

Example:

package main

import "fmt"

func main() {
    s := make([]int, 1000000) // allocate a large slice
    fmt.Println(len(s))
    // After exiting the function, s becomes inaccessible and will be collected by GC
}

Here, after the function completes, the memory occupied by the slice will be automatically freed by the garbage collector.