Skip to content

Instantly share code, notes, and snippets.

@lalizita
Last active December 28, 2022 14:18
Show Gist options
  • Save lalizita/f57b76fef2ae6fa9d822ef1023d24534 to your computer and use it in GitHub Desktop.
Save lalizita/f57b76fef2ae6fa9d822ef1023d24534 to your computer and use it in GitHub Desktop.
closure example with anonymous function in Go
func status() func() string {
var index int
orderStatus := map[int]string{
1: "TO DO",
2: "DOING",
3: "DONE",
}
// Retorna função que tem acesso à todo o escopo
// da função status, portanto também pode atualizar
// o valor da variável index
return func() string {
index++
return orderStatus[index]
}
}
func main() {
update1 := status()
update2 := status()
fmt.Println(update1())
fmt.Println(update1())
fmt.Println(update1())
fmt.Println(update2())
fmt.Println(update2())
}
// OUTPUT
// TO DO
// DOING
// DONE
// TO DO
// DOING
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment