In Go, when using a make statement, for example, allocating megabytes of memory
make([]byte, 1024*1024*d)
Is there a way to determine how much memory is free, before asking for more memory?
In Go, when using a make statement, for example, allocating megabytes of memory
make([]byte, 1024*1024*d)
Is there a way to determine how much memory is free, before asking for more memory?
Yes there is. You can use the gopsutil package:
package main
import (
"fmt"
"github.com/shirou/gopsutil/mem"
)
func main() {
vm, err := mem.VirtualMemory()
if err != nil {
panic(err)
}
fmt.Printf("Total:%d, Available:%d, Used:%d", vm.Total, vm.Available, vm.Used)
}
There are also lots of ways to get this information that are OS-specific. None of them are perfect, but they'll give you something.
You could also have Max Memory as a configuration variable and use: http://godoc.org/runtime#MemStats.