In this subsection, you will learn how to read from a channel. You can read a single value from a channel named c by executing <-c. In this case, the direction is from the channel to the outer world.
The name of the program that I will use to help you understand how to read from a channel is readCh.go, and it will be presented in three parts.
The first code segment from readCh.go is shown in the following Go code:
package main import ( "fmt" "time" ) func writeToChannel(c chan int, x int) { fmt.Println("1", x) c <- x close(c) fmt.Println("2", x) }
The implementation of the writeToChannel() function is the same as before.
The second part of readCh.go follows next:
func main() { c := make(chan int) go writeToChannel(c, 10) time.Sleep(1 * time.Second) fmt.Println("Read:", <-c) time.Sleep(1 * time.Second)
In the preceding code, you read from the c channel using the <-c notation. If you want to store that value to a variable named k instead of just printing it, you can use a k := <-c statement. The second time.Sleep(1 * time.Second) statement gives you the time to read from the channel.
The last code portion of readCh.go contains the following Go code:
_, ok := <-c if ok { fmt.Println("Channel is open!") } else { fmt.Println("Channel is closed!") } }
In the preceding code, you can see a technique for determining whether a given channel is open or not. The current Go code works fine when the channel is closed; however, if the channel were open, the Go code presented here would have discarded the read value of the channel because of the use of the _ character in the _, ok := <-c statement. Use a proper variable name instead of _ if you also want to read the value of the channel in case it is open.
Executing readCh.go will generate the following output:
$ go run readCh.go 1 10 Read: 10 2 10 Channel is closed! $ go run readCh.go 1 10 2 10 Read: 10 Channel is closed!
Although the output is still not deterministic, both the fmt.Println(x) statements of the writeToChannel() function are executed because the channel is unblocked when you read from it.