Sobes.tech
Junior — Middle

Selgitage Go keele automaatse prügikoristuse mehhanismi ja kuidas see mälu haldab.

sobes.tech AI

Vastus AI-lt

In the Go language, an automatic garbage collector (Garbage Collector, GC) is used, which manages memory by freeing unused objects.

The mechanism is based on an algorithm for tracing and counting the reachability of objects:

  • Go starts garbage collection in parallel with program execution (concurrent GC).
  • GC determines which objects in the heap are no longer reachable from root references (e.g., global variables, goroutine stacks).
  • Unreachable objects are considered garbage and are freed.

Features:

  • Go uses a three-generation collection: mark (mark reachable objects), sweep (free unreachable objects).
  • Garbage collection minimizes pauses so as not to block program execution.
  • Memory management is automatic; the programmer does not need to explicitly free memory.

Example:

func main() {
    s := make([]int, 1000000) // allocate memory
    // use s
    s = nil // now the slice is unreachable
    // GC will free memory on the next run
}

Thus, Go simplifies memory management, reducing the likelihood of leaks and errors.