Sobes.tech
Middle+

Kas on võimalik Go-s otseselt välja kutsuda prügikoristus?

sobes.tech AI

Vastus AI-lt

In Go, you can explicitly invoke the garbage collector using the runtime.GC() function. This forcibly starts the garbage collection process, but in real applications, it is generally not recommended to do this frequently, as Go manages memory efficiently on its own.

Example:

package main

import (
    "fmt"
    "runtime"
)

func main() {
    var m runtime.MemStats
    runtime.ReadMemStats(&m)
    fmt.Printf("Before GC: %d bytes\n", m.Alloc)

    runtime.GC() // forced call to garbage collector

    runtime.ReadMemStats(&m)
    fmt.Printf("After GC: %d bytes\n", m.Alloc)
}

Use runtime.GC() only in exceptional cases when you really need to control the timing of garbage collection.