Sobes.tech
Middle+

What is a channel in Go? What are channels used for?

sobes.tech AI

Answer from AI

In Go, a channel is a mechanism for transmitting data between goroutines (lightweight threads). Channels provide safe and synchronized communication, allowing goroutines to exchange values without using shared variables and locks.

Channels are declared with the type of data they transmit, for example:

ch := make(chan int) // channel for transmitting integers

Main operations with channels:

  • Sending a value: ch <- value
  • Receiving a value: value := <-ch

Channels are used for:

  • Synchronizing goroutines
  • Transmitting data between goroutines
  • Organizing data processing pipelines

Example:

package main

import (
	"fmt"
	"time"
)

func worker(ch chan int) {
	for val := range ch {
		fmt.Println("Received:", val)
	}
}

func main() {
	ch := make(chan int)
	go worker(ch)

	for i := 0; i < 5; i++ {
		ch <- i
	}
	close(ch) // close the channel to end the worker
	time.Sleep(time.Second)
}

In this example, the channel is used to transmit numbers from the main goroutine to the worker, which prints them.

What is a channel in Go? What are channels used for… - sobes.tech