GoGo
BeginnerLesson 5 of 15

Functions – Go

Multiple return values, variadic parameters and closures.

You define functions with func; parameter types come after the names. Go functions may return multiple values – usually a result and an error. There are no default values for parameters and no overloading.

package main

import (
	"errors"
	"fmt"
)

func begruesse(name, gruss string) string {
	return gruss + ", " + name + "!"
}

func teile(a, b float64) (float64, error) {
	if b == 0 {
		return 0, errors.New("Division by zero")
	}
	return a / b, nil
}

func main() {
	fmt.Println(begruesse("Ada", "Hello"))
	if erg, err := teile(6, 3); err == nil {
		fmt.Println(erg) // 2
	}
	_, err := teile(1, 0)
	fmt.Println(err) // Division by zero
}

Variadic parameters (...int) collect any number of arguments in a slice; with werte... you pass a slice on. Return values may be named – then a bare return is enough.

package main

import "fmt"

func summe(zahlen ...int) int {
	t := 0
	for _, z := range zahlen {
		t += z
	}
	return t
}

func minMax(werte []int) (lo, hi int) {
	lo, hi = werte[0], werte[0]
	for _, w := range werte {
		if w < lo {
			lo = w
		}
		if w > hi {
			hi = w
		}
	}
	return // returns lo and hi
}

func main() {
	fmt.Println(summe(1, 2, 3, 4)) // 10
	fmt.Println(summe([]int{5, 6}...)) // 11
	fmt.Println(minMax([]int{4, 9, 2})) // 2 9
}

Functions are values: you can store them, pass them around and return them as closures that keep the variables of their surroundings.

package main

import "fmt"

func zaehler() func() int {
	c := 0
	return func() int {
		c++
		return c
	}
}

func main() {
	next := zaehler()
	fmt.Println(next(), next(), next()) // 1 2 3

	quadrat := func(x int) int { return x * x }
	fmt.Println(quadrat(7)) // 49
}
TipA lowercase first letter = visible only within its own package (begruesse), an uppercase first letter = usable from outside (Println). This replaces public and private.