Fundamentos de Go
Go Functions and Multiple Return Values
Functions in Go can return several values. Learn the result-and-error pattern and variadic parameters.
Lo que aprenderás
- Parameters and results
- Returning a value and an error
- Variadic functions
divide(a, b)
divide(10, 4)2.5, nildivide(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.
Puntos clave
- A function can return more than one value.
- nil means there was no error.
- _ ignores a value you do not need.
Ejemplo ejecutable de Go
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))
}
20
2.5
cannot divide by zero
10Practica
Abre el ejemplo en el compilador online, cambia un valor o añade una línea y predice la salida antes de ejecutarlo. Después rompe el código a propósito y lee el mensaje del compilador.
¿Terminaste esta lección?
Márcala como aprendida para seguir tu progreso.
Tu progreso está guardado en este navegador Inicia sesión para conservarlo en todos tus dispositivos.
Practica con un reto
Usa lo que cubre esta lección para resolver un problema real. Cada reto se ejecuta en el navegador, con pruebas al instante y una revisión de IA.
- El mayor de tres Elige el mayor de tres números sin usar una función máxima incorporada. Fácil
- Celsius a Fahrenheit Convierte una temperatura de grados Celsius a grados Fahrenheit. Fácil