vkorbes/aprendago

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

Opened this issue · 1 comments

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!

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.