Question on buffered channels

I don’t understand why a buffered channel is only returning one item.
Playground: playground

package main

import (
“fmt”
“sync”
)

func Func1(wg *sync.WaitGroup, c chan string) {
c <- “one1”
c <- “one2”
wg.Done()
}

func Func2(wg *sync.WaitGroup, c chan string) {
c <- “two1”
c <- “two2”
c <- “two3”
wg.Done()
}

func main() {
var wg sync.WaitGroup
var results []string = make([]string, 20)

c1 := make(chan string, 10)
c2 := make(chan string, 10)
wg.Add(2)
go Func1(&wg, c1)
go Func2(&wg, c2)

wg.Wait()
close(c1)
close(c2)

results = append(results[:], <-c1)

results = append(results[:], <-c2)

fmt.Printf("size=%d, cap=%d, type=%T v=%v\n", len(results), cap(results), results, results)
for p, pv := range results {
	fmt.Println(p, pv)
}

}

2 Likes

You’re only reading from it once, in each append. Try:

for v := range c1 {
  results = append(results, v)
}
3 Likes

Thanks Jacob, that did the trick!

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.