Go from Zero 05. Functions Example

Min Max and Clamp

Functions that call other functions to keep a value within a range.

package main

import "fmt"

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

func clamp(value, low, high int) int {
	return max(low, min(value, high))
}

func main() {
	fmt.Println(min(3, 7))          // 3
	fmt.Println(max(3, 7))          // 7
	fmt.Println(clamp(150, 0, 100)) // 100
	fmt.Println(clamp(-5, 0, 100))  // 0
	fmt.Println(clamp(50, 0, 100))  // 50
}
▶ Open Go Playground

Copy the code above and paste to run

© 2026 ByteLearn.dev. Free courses for developers. · Privacy