The code below is a code that puts a value into a channel and receives and print as much as you put in. I expected it to work, but an error occurs.
package main
import (
"fmt"
"time"
)
func main() {
var ch chan int
for i := 0; i < 3; i++ {
go func(idx int) {
ch <- (idx + 1) * 2
}(i)
}
fmt.Println("result:", <-ch)
fmt.Println("result:", <-ch)
fmt.Println("result:", <-ch)
//do other work
time.Sleep(2 * time.Second)
}
Tested on playground - https://go.dev/play/p/FFmoSMheNfu