I'm new with golang. I'm trying to understand how channels work, but it's really confusing.
I commented my questions. Can someone explain to me why this code behaves in this strange way?
package main
import "fmt"
func main() {
slice := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}
c := make(chan int)
go pokeVals(slice, c)
fmt.Println(slice)
fmt.Println("start")
<-c // why 2 "poke"s here?
fmt.Println("-")
<-c // why 0 "poke"s?
//<-c // But if uncommented - 2 more "pokes" here
fmt.Println("end")
}
func pokeVals(values []int, c chan int) {
for _, val := range values {
fmt.Println("poke")
c <- val
}
fmt.Println("overpoked")
}
Golang playground link: https://play.golang.org/p/u__cVyUbNJY