Soft Memory Limit With debug.SetMemoryLimit
Cap the Go runtime with debug.SetMemoryLimit: read the previous limit, set a soft ceiling, and restore it without a hard crash.
Code
package main
import (
"fmt"
"runtime/debug"
)
func main() {
// soft memory limit:软上限让 GC 更努力回收,而不是像硬上限那样崩溃
prev := debug.SetMemoryLimit(32 << 20)
fmt.Println("default limit was:", prev)
// 传 -1 只读取当前值,不修改
fmt.Println("current limit:", debug.SetMemoryLimit(-1))
debug.SetMemoryLimit(prev) // 用完恢复,不影响宿主进程
fmt.Println("restored:", debug.SetMemoryLimit(-1))
}The runtime story
Everything happens inside the function main.
What to watch for
- Runs on the standard library alone; nothing to install.
Using it
The signature at the center: func main()
The demo output is labeled (default limit was:, current limit:, restored:), so the output doubles as a step-by-step trace of what the file did.
Key statements
func main() {
// soft memory limit:软上限让 GC 更努力回收,而不是像硬上限那样崩溃
prev := debug.SetMemoryLimit(32 << 20)
fmt.Println("default limit was:", prev)
// 传 -1 只读取当前值,不修改
fmt.Println("current limit:", debug.SetMemoryLimit(-1))
debug.SetMemoryLimit(prev) // 用完恢复,不影响宿主进程
fmt.Println("restored:", debug.SetMemoryLimit(-1))
}
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.Kubernetes Resource CalculatorCalculate per-pod and cluster CPU and memory requests, limits, QoS class, overcommit ratios, headroom, and node fit estimates for Kubernetes workloads.
FAQ
- What does Soft Memory Limit With debug.SetMemoryLimit print when run?
- Execute the whole file; each printed line is prefixed with a label like `default limit was:`, `current limit:`, `restored:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.