February 2018
Intermediate to advanced
246 pages
6h 3m
English
A channel is a communication mechanism that allows us to pass data between goroutines. It is an in-built data type in Go. Data can be passed using one of the primitive data types or we can create our own complex data type using structs.
Here is a simple example to demonstrate how to use a channel:
// simchan.go
package main
import "fmt"
// helloChan waits on a channel until it gets some data and then prints the value.
func helloChan(ch <- chan string) {
val := <- ch
fmt.Println("Hello, ", val)
}
func main() {
// Creating a channel
ch := make(chan string)
// A Goroutine that receives data from a channel
go helloChan(ch)
// Sending data to a channel.
ch <- "Bob"
}
If we run the preceding code, it would print the following ...
Read now
Unlock full access