Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

golang
channel
concurrency

What are channels in Golang?

Educative Answers Team

In Golang, or Go, channels are a means through which different goroutinesa lightweight thread of execution in Go communicate.

Think of them as pipes through which you can connect with different concurrent goroutines. The communication is bidirectional by default, meaning that you can send and receive values from the same channel.

Moreover, by default, channels send and receive until the other side is ready. This allows goroutines to synchronize without explicit locks or condition variables.

svg viewer
Sending data from one goroutine to another

Syntax

  1. Make a channel: make(chan [value-type]), where [value-type] is the data type of the values to send and receive, e.g., int.

  2. Send and receive values: channel <- and <- channel,
    where <- is the channel operator.

  3. Close a channel: close(channel).
    After closing, no value will be sent to the channel.

Both sending and receiving are blocking operations by default.

Implementation

  • We make a channel with the type string and start function greet as a goroutine.
  • The function greet is blocked when it encounters <- c and waits to receive a value.
  • The main goroutine sends a value to the channel, which is then printed by the greet function.
package main
import "fmt"

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

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

func main() {

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

	// Starting a concurrent goroutine
	go greet(c)

	// Sending values to the channel c
	c <- "World"

	// Closing channel
	close(c)
}

RELATED TAGS

golang
channel
concurrency
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring