In this tutorial, We are going to learn about GC function in runtime package in go with example and in details.
The ‘GC‘ function in runtime package in go is to trigger a garbage collection, a mechanism that frees up memory that’s no longer needed by automatically reclaiming resources that the program doesn’t use anymore.
Syntax:
func GC()
This function does not accept any arguments and does not return any value. When called, it forces the garbage collector to run immediately.
Example:
package main
import (
"fmt"
"runtime"
"runtime/debug"
)
func main() {
s := "Go GC function"
fmt.Println(s)
// Discard the string
s = ""
// Call GC explicitly
debug.SetGCPercent(-1) // disable automatic GC
runtime.GC()
fmt.Println("GC run completed")
}
In this example, we first create a string variable ‘s‘ and then discard it by setting it to an empty string. We disable automatic garbage collection using debug.SetGCPercent(-1)
and then call runtime.GC()
to manually trigger garbage collection.
Output:
Go GC function GC run completed
To learn more about golang, You can refer given below link:
https://techieindoor.com/go-runtime-package-in-go/
References: