Sobes.tech
Junior — Middle

How to organize interaction and data transfer through channels in a system?

sobes.tech AI

Answer from AI

In Go, interaction between goroutines is often organized through channels — typed pipelines for data transfer.

To send data, a channel is created using make(chan Type). Goroutines can send data to the channel using the <- operator, and receive from the channel with the same operator, which ensures synchronization.

Example:

package main

import (
    "fmt"
    "time"
)

func producer(ch chan<- int) {
    for i := 0; i < 5; i++ {
        ch <- i // sending data
        time.Sleep(time.Millisecond * 500)
    }
    close(ch) // closing the channel to signal completion
}

func consumer(ch <-chan int) {
    for val := range ch { // receiving data from the channel
        fmt.Println("Received:", val)
    }
}

func main() {
    ch := make(chan int)
    go producer(ch)
    consumer(ch)
}

Thus, channels allow safe and efficient data transfer between goroutines, avoiding race conditions and deadlocks.

How to organize interaction and data transfer through… - sobes.tech