I'm trying to understand channels in Go. Here is a code example:
package main
import "fmt"
func main() {
m := make(map[int]string)
m[2] = "First Value"
c := make(chan bool)
go func() {
m[2] = "Second Value"
c <- true
}()
fmt.Printf("1-%s
", m[2])
fmt.Printf("2-%s
", m[2])
_ = <-c
fmt.Printf("3-%s
", m[2])
fmt.Printf("4-%s
", m[2])
}
Sometimes the output of the above code was (result 1):
1-First Value
2-First Value
3-Second Value
4-Second Value
but sometimes I got (result 2):
1-First Value
2-Second Value
3-Second Value
4-Second Value
After changing c := make(chan bool)
to c := make(chan bool, 1)
, the same occurred: sometimes result 1, sometimes result 2.
Why?