aprendago
aprendago copied to clipboard
Exercício: Capítulo 13, Exercício 4 (Nível: 6)
Exercício: Capítulo 13, Exercício 4 (Nível: 6)
Use esta thread para compartilhar sua solução, discutir o exercício com os colegas e pedir ajuda caso tenha dificuldades!
https://play.golang.org/p/-OrWHoML2hb
Encontrei uma maneira diferente ,de trazer os numero pares de 0-10
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 soma() func() int {
a := 0
b := 0
return func() int {
a++
b++
return a + b
}
}
func main() {
total := soma()
fmt.Println(total())
fmt.Println(total())
fmt.Println(total())
fmt.Println(total())
fmt.Println(total())
}
Output
2
4
6
8
10
Program exited.
package main
import "fmt"
func main() {
a := queRetorna()
fmt.Println(a())
}
func queRetorna() func() int {
x := 1
return func() int {
x++
return x
}
}
package main
import "fmt"
func main() {
fmt.Println("Primeiro escopo:")
f := closureexemplo(7)
fmt.Println(f())
fmt.Println(f())
fmt.Println(f())
fmt.Println(f())
fmt.Println("Segundo escopo:")
x := closureexemplo(9)
fmt.Println(x())
fmt.Println(x())
fmt.Println(x())
fmt.Println(x())
}
func closureexemplo(x int) func() int {
total := 0
return func() int {
total += x
return total
}
}
Output
Primeiro escopo:
7
14
21
28
Segundo escopo:
9
18
27
36
Cap. 13 – Exercícios: Nível #6 – 10 https://go.dev/play/p/5jHzERbeEPC
https://go.dev/play/p/MCrc2o2ZctP
package main
import "fmt"
func main() {
value := Closure()
fmt.Println("ultimo valor: ", value())
}
func Closure() func() int {
x := 1
return func() int {
for i := 0; i <= 20; i++ {
if i%2 == 0 {
fmt.Println("valor par: ", i)
x = i
}
}
return x
}
}