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 4 (Nível: 6) #50

Open vkorbes opened 3 years ago

vkorbes commented 3 years ago

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!

an4kein commented 3 years ago

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.
alansantosmg commented 3 years ago
package main

import "fmt"

func main() {

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

}

func queRetorna() func() int {
    x := 1
    return func() int {
        x++
        return x
    }
}
gomesmatheus commented 2 years ago
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
wfrsilva commented 2 years ago

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

image

Harsgaard commented 1 year ago

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

UdsonWillams commented 3 months ago
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
    }
}