Instagram
youtube
Facebook
  • 1 year, 6 months ago
  • 963 Views

Channel in Golang Tutorial with Example

Yaman Birla
Table of Contents

As we have talked about concurrency in golang earlier. So, now we are going to follow up on the previous blog regarding concurrency and what is Goroutine's work. Similarly, Channels are an important topic in concurrency.

In Golang, Channel refers to the pipelines or a medium through which different goroutines communicate with each other. Channel is bidirectional in nature means that one goroutine can send or receive data through the same channel. Also, this communication is lock-free as goroutines synchronize. For a better understanding please refer to the image below.

 

 

Now, let’s learn about the implementation and syntax of channel in Golang

 

Syntax:

Firstly, we make a channel as shown below

 

make(chan [value-type]) here, value-type indicates the type of data that are going to send and receive in communication.

 

channel <- and <- channel are the send and receive values, where <- is the channel operator.

Channel closing: close(channel).

No value will be transmitted to the channel once it has been closed.

 

Note regarding channel:

Blocking Send and Receive: When data is transmitted to a channel, the control in that send statement is blocked until another goroutine reads from that channel. Similarly, when a channel gets data from a goroutine, the read command is blocked until the next goroutine statement is executed.

 

Zero Value Channel: The channel's zero value is nil.

 

For the Channel loop: A for loop can traverse over the channel's successive values until it closes.

 

Coding a Channel in Golang

We create a channel of type string and run the greet function as a goroutine.

When it detects - P, the function greet is blocked and waits for a value.

The main goroutine transmits a value to the channel, which the hello function prints.

 


package main
import "fmt"

// Prints a greeting message using values received in
// the channel
func greet(p chan string) {

	name := <- p	// receiving value from channel
	fmt.Println("Hello", name)
}

func main() {

	// Making a channel of value type string
	p := make(chan string)

	// Starting a concurrent goroutine
	go greet(p)

	// Sending values to the channel c
	p <- "Yaman"

	// Closing channel
	close(p)
}

 

 

Add a comment: