I have following code
import (
"fmt"
)
func access(ch chan int) {
for elem := range ch {
fmt.Println(elem) // prints only one as well
}
fmt.Println(<-ch) // prints the value
fmt.Println(<-ch) // doesn't print
}
func main() {
ch := make(chan int)
go access(ch)
ch <- 55 // blocks the main routine
ch <- 56 // this value never prints
fmt.Println("Hello, World!")
}
Why only the first value sent through channel gets printed not the other one ,even with for loop ,inspite of using unbuffered channel
If I use a for loop to send values it works
arr:=[]int{1, 1, 1, 1, 1}
for elem := range arr {
ch<-elem
}
Here is another mystery ,if I add three values sending to ch.All values gets printed in the access function .this is bit strange .....................
func access(ch chan int){
/*
for elem := range ch {
fmt.Println(elem)
}
*/
// All prints
fmt.Println(<-ch)
fmt.Println(<-ch)
fmt.Println(<-ch)
}
func main() {
go access(ch)
ch<-55
ch<-56
ch<-57
}