vkorbes / aprendago

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

Exercício: Capítulo 22, Exercício 3 (Nível: 10) #68

Open vkorbes opened 3 years ago

vkorbes commented 3 years ago

Exercício: Capítulo 22, Exercício 3 (Nível: 10)

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!

haystem commented 3 years ago

Desculpa mas passei a faca no receive :100: https://play.golang.org/p/BrNmZKoKHvC

an4kein commented 3 years ago

https://play.golang.org/p/V1ujzDWFyjb

fritei

package main

import (
    "fmt"
    "sync"
)

var wg sync.WaitGroup

func main() {
    c := gen()
    go receive(c)
    wg.Wait()
    fmt.Println("about to exit")
}

func gen() <-chan int {
    c := make(chan int)
    wg.Add(1)
    go func() {
        for i := 0; i < 100; i++ {
            c <- i
        }
        wg.Done()
    }()

    return c
}

func receive(z <-chan int) {
    for i := range z {
        fmt.Println(i)

    }
    return
}

Output

[...]
94
95
96
97
98
99
about to exit

Program exited.
Harsgaard commented 1 year ago

Antes de ver a solução: https://go.dev/play/p/rw7x1bfYrPl depois: https://go.dev/play/p/_OP7R9Sumdy

LelecoNN commented 8 months ago

Playground

package main

import (
    "fmt"
)

func main() {
    c :=make(chan int)
    go gen(c)
     receive(c)
    fmt.Println("about to exit")

}

func gen(c chan int) <-chan int { 
    for i := 0; i < 100; i++ {
        c <- i
    }
    close(c)
    return c
}
func receive(c <-chan int) {
    for v := range c {
        fmt.Println(v)
    }
}