vkorbes / aprendago

Curso completo em português da linguagem Go, de zero a ninja! 🇧🇷
http://aprendago.com
1k stars 179 forks source link

Exercício: Capítulo 13, Exercício 11 (Nível: 6) #51

Open vkorbes opened 3 years ago

vkorbes commented 3 years ago

Exercício: Capítulo 13, Exercício 11 (Nível: 6)

Link para o vídeo:

Use esta thread para compartilhar sua solução, discutir o exercício com os colegas e pedir ajuda caso tenha dificuldades!

an4kein commented 3 years ago

Video: https://youtu.be/cpo83EFi3ts exercício: https://play.golang.org/p/HQGjBUOaHUt

package main

import "fmt"

/* - Demonstre o funcionamento de um closure.
- Ou seja: crie uma função que retorna outra função,
onde esta outra função faz uso de uma variável alem de seu scope.
*/

func alem() func() int {
    x := 0
    y := 0
    fmt.Println(x, y)
    return func() int {
        x++
        y++
        fmt.Println(x, y)
        return x + y
    }
}

func main() {
    a := alem()
    b := alem()
    c := alem()

    fmt.Println(a())
    fmt.Println(b())
    fmt.Println(b())
    fmt.Println(b())
    fmt.Println(b())
    fmt.Println(c())
    fmt.Println(c())
    fmt.Println(c())

}

Output

0 0
0 0
0 0
1 1
2
1 1
2
2 2
4
3 3
6
4 4
8
1 1
2
2 2
4
3 3
6

Program exited.