O'Reilly logo

Distributed Computing with Go by V.N. Nikhil Anurag

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

What is a channel?

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required