Temas importantes de Go

Go Closures and Function Values

Functions are values in Go: store them, pass them, return them, and let them remember variables.

  • Intermedio
  • 3 min de lectura
  • 1 ejemplo ejecutable
Lo que aprenderás
  • Functions as values
  • Closures keep state
  • Passing a function
next := counter()
1next()
2next()
3next()
count lives on between calls.

A function that remembers

In Go a function is a value: you can store it in a variable, pass it to another function or return it. A closure is a function that keeps using variables from the place where it was created.

counter returns a function that remembers its own count between calls, and each call to counter creates a separate count. apply takes a function as a parameter. The function literal passed to apply reads bonus from main.

Puntos clave

  1. counter returns a function with its own count.
  2. Each call to counter starts a new count.
  3. A function literal can use variables around it.

Ejemplo ejecutable de Go

Go
Ejecutar código →
main.go
package main

import "fmt"

func counter() func() int {
	count := 0
	return func() int {
		count++
		return count
	}
}

func apply(values []int, transform func(int) int) []int {
	result := make([]int, len(values))
	for i, value := range values {
		result[i] = transform(value)
	}
	return result
}

func main() {
	next := counter()
	fmt.Println(next(), next(), next())

	other := counter() // a separate count
	fmt.Println(other())

	bonus := 10
	fmt.Println(apply([]int{1, 2, 3}, func(n int) int { return n*2 + bonus }))
}
Obtén un botón Run para este ejemplo Resultado de ejecutar el código
1 2 3
1
[12 14 16]

Practica

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.

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.

Todos los retos