get system free memory in go

You can get the system's free memory in Go using the os package.

Here's an example code snippet:

main.go
package main

import (
    "fmt"
    "runtime"
)

func main() {
    var m runtime.MemStats
    runtime.ReadMemStats(&m)

    // Print total allocated memory to date:
    fmt.Println("Alloc:", m.Alloc)

    // Print how much memory is still in use:
    fmt.Println("HeapAlloc:", m.HeapAlloc)

    // Print how much memory can be released to the OS:
    fmt.Println("Sys:", m.Sys)

    // Print system free memory:
    fmt.Println("Free:", m.Sys - m.HeapAlloc)
}
461 chars
24 lines

In this code, we are using the runtime package to read the memory statistics of the Go program. We then use the MemStats struct to get the amount of allocated memory, the amount of heap memory still in use, the amount of memory (including virtual memory) obtained from the system and finally the amount of free memory in the system.

gistlibby LogSnag