Menu Close

GC in runtime package in go

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.


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.


package main

import (





func main() {

    s := "Go GC function"


    // Discard the string
    s = ""

    // Call GC explicitly
    debug.SetGCPercent(-1) // disable automatic 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.


Go GC function
GC run completed

To learn more about golang, You can refer given below link:


Posted in golang, packages, runtime

Leave a Reply

Your email address will not be published. Required fields are marked *