Go Tutorial · Functions and Methods · Lesson 17 of 30

Go Functions

Parameters, multiple return values, named results and variadic functions.

Declaring functions

Types come after names. Consecutive parameters of the same type can share it:

Example 1
package main

import (
	"fmt"
	"strings"
)

func add(a, b int) int {
	return a + b
}

func greet(name string, times int) string {
	return strings.Repeat("Hi "+name+"! ", times)
}

func main() {
	fmt.Println(add(2, 3))
	fmt.Println(greet("Ada", 3))
}

Output

5
Hi Ada! Hi Ada! Hi Ada! 

Run this on your computer — see “Get Started” for setup.

Multiple return values

Functions can return several values — most often a result and an error:

Example 2
package main

import (
	"errors"
	"fmt"
)

func divmod(a, b int) (quotient, remainder int) { // named results
	quotient = a / b
	remainder = a % b
	return
}

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

func main() {
	q, r := divmod(17, 5)
	fmt.Println(q, r)
	if _, err := safeDivide(1, 0); err != nil {
		fmt.Println("error:", err)
	}
	v, _ := safeDivide(10, 4)
	fmt.Println(v)
}

Output

3 2
error: division by zero
2.5

Run this on your computer — see “Get Started” for setup.

Variadic functions

...T accepts any number of arguments as a slice; slice... spreads a slice into them:

Example 3
package main

import "fmt"

func sum(nums ...int) int {
	total := 0
	for _, n := range nums {
		total += n
	}
	return total
}

func main() {
	fmt.Println(sum(), sum(1, 2), sum(1, 2, 3, 4))
	nums := []int{10, 20, 30}
	fmt.Println(sum(nums...))
}

Output

0 3 10
60

Run this on your computer — see “Get Started” for setup.

Test yourself

How does a Go function usually report failure?

  1. By throwing an exception
  2. By returning an error as its last value
  3. By returning -1
  4. By calling panic
Show answer

Answer: By returning an error as its last value