How can I print the contents of a channel in Go?
For example:
package main
import "fmt"
func main() {
ok := make(chan int)
ok <- 1
x := <- ok
fmt.Println(x)
}
As I understand, ok
is a channel which can store an integer value. So, how can I print its contents?
fmt.Println(ok)
doesn't print the value stored inside the channel.
Thanks.
Channels make(chan int)
has implicit size zero ( ref: https://golang.org/ref/spec#Making_slices_maps_and_channels)
A channel of size zero is unbuffered. A channel of specified size make(chan int, n) is buffered. See http://golang.org/ref/spec#Send_statements for a discussion on buffered vs. unbuffered channels. The example at http://play.golang.org/p/VZAiN1V8-P illustrates the difference.
Here, channel <-ok
or ok <-
will be blocked until someone processes it (concurrently). So, change ok := make(chan int)
to ok := make(chan int,1)
package main
import "fmt"
func main() {
ok := make(chan int, 1)
ok <- 1
x := <- ok
fmt.Println(x)
}
Or concurrently proccess it
package main
import "fmt"
func main() {
ok := make(chan int)
go func(){
ok <- 1
}()
x := <- ok
fmt.Println(x)
}
Here you are trying to write to an unbuffered channel since there are no go routines trying to read from the channel it will reach a deadlock situation
Here is what you can do
package main
import (
"fmt"
"time"
)
func main() {
ok := make(chan int)
go func() {
for x := range ok {
fmt.Println(x)
}
}()
ok <- 1
ok <- 3
ok <- 2
ok <- 5
ok <- 3
ok <- 9
time.Sleep(1)
}
you may find the link to play ground here