aprendago icon indicating copy to clipboard operation
aprendago copied to clipboard

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

Open vkorbes opened this issue 4 years ago • 6 comments

Exercício: Capítulo 13, Exercício 4 (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!

vkorbes avatar Sep 30 '20 17:09 vkorbes

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.

an4kein avatar Feb 28 '21 21:02 an4kein

package main

import "fmt"

func main() {

	a := queRetorna()
	fmt.Println(a())

}

func queRetorna() func() int {
	x := 1
	return func() int {
		x++
		return x
	}
}

alansantosmg avatar Apr 25 '21 03:04 alansantosmg

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

gomesmatheus avatar Jan 14 '22 12:01 gomesmatheus

Cap. 13 – Exercícios: Nível #6 – 10 https://go.dev/play/p/5jHzERbeEPC

image

wfrsilva avatar May 30 '22 20:05 wfrsilva

https://go.dev/play/p/MCrc2o2ZctP

Harsgaard avatar Dec 16 '22 00:12 Harsgaard

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
	}
}

UdsonWillams avatar Apr 25 '24 20:04 UdsonWillams