← Вернуться к курсу: Go from scratch

Functions and multiple return values

Видео скоро появится

A function is a named block of code that receives data, does some work and returns a result. It is used to avoid repeating code, to split a big problem into small pieces and to test each piece separately. You have already used functions without knowing it: main is a function and so is fmt.Println. Today you will learn to write your own, and you will discover a very typical Go feature: a function can return more than one value at once.

Declaring and calling functions

The syntax is func name(parameters) returnType { body }. Each parameter has its type after the name, and if several consecutive ones share a type you can write it once: func add(a, b int) int. To return a value you use return. If the function returns nothing, the return type is omitted. Arguments are passed by value: the function receives a copy, so modifying a parameter inside does not change the caller's original variable.

go
package main

import "fmt"

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

func greet(name string) {
	fmt.Println("Hello,", name)
}

func double(n int) int {
	n = n * 2 // changes only the local copy
	return n
}

func main() {
	greet("Ana")
	x := 5
	fmt.Println(add(x, 3), double(x), x) // 8 10 5
}

Multiple return values

A function can return several values by declaring them in parentheses: func divide(a, b float64) (float64, bool). The caller receives all of them with a multiple assignment. This mechanism is the basis of error handling in Go: the convention is that the last value is of type error, as we will see in the next lesson. If you do not need one of the returned values, discard it with the underscore, because Go does not allow unused variables.

go
package main

import "fmt"

func divide(a, b float64) (float64, bool) {
	if b == 0 {
		return 0, false
	}
	return a / b, true
}

// named results: rectangle returns area and perimeter
func rectangle(w, h float64) (area, perimeter float64) {
	area = w * h
	perimeter = 2 * (w + h)
	return // naked return uses the named results
}

func main() {
	if result, ok := divide(10, 4); ok {
		fmt.Println(result) // 2.5
	}
	_, ok := divide(1, 0)
	fmt.Println(ok) // false

	a, p := rectangle(3, 4)
	fmt.Println(a, p) // 12 14
}

Variadic functions and functions as values

If the last parameter has three dots before the type, like nums ...int, the function accepts any number of arguments, and inside it receives them as a slice. When calling it with an existing slice, add three dots after it: sum(values...). In Go functions are first-class values: you can store them in variables, pass them as arguments and return them from other functions. A function without a name, written where it is needed, is called an anonymous function, and if it uses variables from its surroundings it is called a closure, because it remembers them even after the outer function has finished.

go
package main

import "fmt"

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

func counter() func() int {
	c := 0
	return func() int { // closure over c
		c++
		return c
	}
}

func main() {
	fmt.Println(sum(), sum(1, 2, 3)) // 0 6
	next := counter()
	fmt.Println(next(), next(), next()) // 1 2 3
}
  • Parameters are passed by value (copies).
  • Several returns: func f() (int, error).
  • Named results allow a bare return, but use it only in short functions.
  • ...T receives any number of arguments as a slice.
  • Functions are values: they can be assigned and passed.

✎ Мои заметки

Сохранено только в этом браузере. Войдите, чтобы хранить в аккаунте.0/5000 символов

← НазадДалее →