The exact output of your program is not defined and depends on the scheduler. The scheduler can choose freely between all goroutines that are currently not blocked. It tries to run those goroutines concurrently by switching the current goroutine in very short time intervals so that the user gets the feeling that everything happens simultanously. In addition to that, it can also execute more than one goroutine in parallel on different CPUs (if you happen to have a multicore system and increase runtime.GOMAXPROCS). One situation that might lead to your output is:
main
creates two goroutines- the scheduler chooses to switch to one of the new goroutines immediately and chooses
display
display
prints out the message and is blocked by the channel send (c <- true
) since there isn't a receiver yet.- the scheduler chooses to run
sum
next - the sum is computed and printed on the screen
- the scheduler chooses to not resume the
sum
goroutine (it has already used a fair amount of time) and continues withdisplay
display
sends the value to the channel- the scheduler chooses to run main next
- main quits and all goroutines are destroyed
But that is just one possible execution order. There are many others and some of them will lead to a different output. If you want to print just the first result and quit the program afterwards, you should probably use a result chan string
and change your main
function to print fmt.Println(<-result)
.