Last active
December 28, 2022 14:18
-
-
Save lalizita/f57b76fef2ae6fa9d822ef1023d24534 to your computer and use it in GitHub Desktop.
closure example with anonymous function in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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