Channels, When the program flow exit from the infinite for { select }

Hey there. I’d say that the main issue and questions here goes from lack of understanding not just the channels, but goroutines in general. It can lead to more misunderstanding and misconceptions in the future. You can solve this by doing a range over a channel for example:

package main

import (
	"fmt"
	"time"
)

func main() {
	var i int

	ch := make(chan int)

	go func() {
		defer close(ch)

		for j := range 10 {
			ch <- j
			time.Sleep(time.Second)
		}
	}()

	for i = range ch {
	}

	fmt.Println(i)
}

In this case at the end, it has the last sent value from the channel. You can add empty struct channel to signalize the exit. You can do it around your send/receive channels. There are more questions than answers, since it’s hard to tell for sure without more code. E.g., where the c.ackCh is closing? What should “timeout” do? is it for logging?

Another topic which is really important is when and how you use buffered channels.