This example returns no output.
package main
import (
"fmt"
)
func main(){
c:=make(chan int) //create un-buffered channel of type int
ints:=[]int{1,2,3,4,5} //slice of ints for testing
go func(){ //kick start goroutitne that sends to the
channel and finally closes it
for _,v:=range ints{
c<-v
}
close(c)
}()
go func() { //kick start goroutine that recieves from the
channel and prints the ints
for v:=range c{
fmt.Println(v)
}
}()
}
But, take away the go keyword from the second goroutine; thus letting to
function run the main goroutine. You get see the prints as expected.
package main
import (
"fmt"
)
func main(){
c:=make(chan int) //create unbuffered chanel of type int
ints:=[]int{1,2,3,4,5} //slice of ints for testing
go func(){ //kick start goroutitne that sends to the chanel
and finally closes it
for _,v:=range ints{
c<-v
}
close(c)
}()
func() { //call function without start gooutine gets
output as expected.
for v:=range c{
fmt.Println(v)
}
}()
}
Now consider this. Similar to the first example with two goroutines but
added another dummy channel that the fist goroutine sends a dummy value and
the main goroutine finally receives it.
package main
import (
"fmt"
)
func main(){
c:=make(chan int) //create unbuffered channel of type int
d:=make(chan int) //dummy unbuffered channel for testing
ints:=[]int{1,2,3,4,5} //slice of ints for testing
go func(){ //kick start goroutitne that sends to the
channel and finally closes it
for _,v:=range ints{
c<-v
}
close(c)
d<-9 //send dummy value to dummy channel and closes it
close(d)
}()
go func() { //kick start goroutine that recieves from the
channel and prints the ints
for v:=range c{
fmt.Println(v)
}
}()
fmt.Println(<-d) //printout dummy value in main goroutine and
vuala!
//you see all the prints from the second
goroutine as well.
}
There is something connected to recieving from a channel in the main
goroutine and seeing prints within goroutines.
Can someone explain this please.
--