Argomenti importanti di Go
Go Closures and Function Values
Functions are values in Go: store them, pass them, return them, and let them remember variables.
Cosa imparerai
- Functions as values
- Closures keep state
- Passing a function
next := counter()
1next()
2next()
3next()
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.
Punti chiave
- counter returns a function with its own count.
- Each call to counter starts a new count.
- A function literal can use variables around it.
Esempio Go eseguibile
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 }))
}
1 2 3
1
[12 14 16]Esercitati
Apri l'esempio nel compilatore online, cambia un valore o aggiungi una riga e prova a prevedere l'output prima di eseguirlo. Poi rompi il codice di proposito e leggi il messaggio del compilatore.
Hai finito questa lezione?
Segnala come imparata per tenere traccia dei tuoi progressi.
I tuoi progressi sono salvati in questo browser Accedi per conservarli su ogni dispositivo.
Esercitati con una sfida
Usa ciò che questa lezione spiega per risolvere un problema reale. Ogni sfida gira nel browser, con test immediati e una revisione dell'IA.
- Ordinare per una chiave scelta Ordina le persone per nome o per età con un comparatore scelto a runtime, risolvendo i pareggi in modo coerente. Facile
- Iscritti agli eventi Consegna gli eventi agli iscritti di ogni argomento, in stile observer, e conta cosa riceve ciascuno. Facile