Functions and errors
Define functions with func, return several values, and return an error instead of throwing.
Runs in Zerethon IDE · Go 1.27
Official Go documentation ↗
main.go
package main
import (
"errors"
"fmt"
)
func greet(name string) string {
return "Hello, " + name + "!"
}
func stats(numbers []int) (int, int, float64) {
low, high, sum := numbers[0], numbers[0], 0
for _, n := range numbers {
low = min(low, n)
high = max(high, n)
sum += n
}
return low, high, float64(sum) / float64(len(numbers))
}
func divide(a, b int) (int, error) {
if b == 0 {
return 0, errors.New("division by zero")
}
return a / b, nil
}
func main() {
fmt.Println(greet("Ada"))
low, high, mean := stats([]int{4, 8, 6})
fmt.Println(low, high, mean)
if _, err := divide(1, 0); err != nil {
fmt.Println("error:", err)
}
q, _ := divide(9, 3)
fmt.Println(q)
square := func(x int) int { return x * x }
fmt.Println(square(9))
}
Output
Hello, Ada! 4 8 6 error: division by zero 3 81
- The type comes after the name:
func divide(a, b int) (int, error). - Go has no exceptions. A function that can fail returns an
erroras its last value; the caller checksif err != nil. _throws a value away. You must take or discard every returned value you assign.minandmaxare built in since Go 1.21.
Tip: Wrap an error with context using fmt.Errorf("reading %s: %w", name, err); errors.Is and errors.As find the original later.