Bases de Go

Go Functions and Multiple Return Values

Functions in Go can return several values. Learn the result-and-error pattern and variadic parameters.

  • Débutant
  • 4 min de lecture
  • 1 exemple exécutable
Ce que vous allez apprendre
  • Parameters and results
  • Returning a value and an error
  • Variadic functions
divide(a, b)
divide(10, 4)2.5, nil
divide(1, 0)0, "cannot divide by zero"

A result and an error

A function groups code under a name. Go functions can return several values, and the usual pattern is to return a result together with an error.

divide returns the result and an error; nil means there was no error. The underscore ignores a value you do not need. numbers ...int accepts any number of integers, and the named result total is returned by the bare return.

Points clés

  1. A function can return more than one value.
  2. nil means there was no error.
  3. _ ignores a value you do not need.

Exemple Go exécutable

Go
Exécuter le code →
main.go
package main

import (
	"errors"
	"fmt"
)

func area(width, height int) int {
	return width * height
}

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

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

func main() {
	fmt.Println(area(4, 5))

	if result, err := divide(10, 4); err == nil {
		fmt.Println(result)
	}
	_, err := divide(1, 0)
	fmt.Println(err)

	fmt.Println(sum(1, 2, 3, 4))
}
Obtenir un bouton Run pour cet exemple Résultat de l'exécution
20
2.5
cannot divide by zero
10

S'entraîner

Ouvrez l'exemple dans le compilateur en ligne, modifiez une valeur ou ajoutez une ligne, et devinez la sortie avant de l'exécuter. Cassez ensuite le code exprès et lisez le message du compilateur.

Leçon terminée ?

Marquez-la comme apprise pour suivre votre progression.

Suivante : Fibonacci Sequence →

S'entraîner avec un défi

Utilisez le contenu de cette leçon pour résoudre un vrai problème. Chaque défi s'exécute dans le navigateur, avec des tests instantanés et une revue par l'IA.

Tous les défis