package main
import (
"errors"
"fmt"
"math"
)
// Basic function
func add(a, b int) int {
return a + b
}
// Multiple return values — the Go idiom for error handling
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("division by zero")
}
return a / b, nil
}
// Named return values
func minMax(nums []int) (min, max int) {
min, max = nums[0], nums[0]
for _, n := range nums[1:] {
if n < min { min = n }
if n > max { max = n }
}
return // "naked" return — returns named values
}
// Variadic function
func sum(nums ...int) int {
total := 0
for _, n := range nums {
total += n
}
return total
}
// Function as a value
func apply(f func(float64) float64, x float64) float64 {
return f(x)
}
func main() {
fmt.Println(add(3, 4)) // 7
result, err := divide(10, 3)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Printf("%.4f\n", result) // 3.3333
}
lo, hi := minMax([]int{3, 1, 4, 1, 5, 9, 2, 6})
fmt.Println(lo, hi) // 1 9
fmt.Println(sum(1, 2, 3, 4, 5)) // 15
// Passing a function
fmt.Printf("%.4f\n", apply(math.Sqrt, 16)) // 4.0000
// Anonymous function / closure
multiplier := func(factor float64) func(float64) float64 {
return func(x float64) float64 {
return x * factor
}
}
double := multiplier(2)
triple := multiplier(3)
fmt.Println(double(5), triple(5)) // 10 15
}