Min Max Builtins Clamp Values

Clamp configuration values into a valid range with the min and max builtins, letting the helper survive swapped low and high bounds.

GoConfig Management

Code

gosnippet
18 lines
package main

import "fmt"

// clamp 用内建 min/max 把 value 限制进 [low, high],上下限传反也能自动纠正
func clamp(value, low, high int) int {
	if low > high {
		low, high = high, low
	}
	return min(max(value, low), high)
}

func main() {
	// 并发 worker 数之类的配置:请求值可能越界
	for _, requested := range []int{-5, 0, 8, 64, 500} {
		fmt.Printf("%d -> %d\n", requested, clamp(requested, 1, 32))
	}
}

Inside the snippet

The part that acts sits in the functions clamp and main — everything else is wiring.

Repetition is confined to for _, requested := range []int{-5, 0, 8, 64, 500} — the rest of the file is straight-line.

Using it

The main signature reads func clamp(value, low, high int) int

Running the file executes main, which drives clamp in order.

Key statements

for _, requested := range []int{-5, 0, 8, 64, 500} {
fmt.Printf("%d -> %d\n", requested, clamp(requested, 1, 32))
}
func clamp(value, low, high int) int {
if low > high {
low, high = high, low
}
return min(max(value, low), high)
}

Interactive Tools for This Topic

FAQ

How do you run Min Max Builtins Clamp Values?
Execute it straight away — the program needs nothing beyond the runtime.