Sobes.tech
Junior — Middle

Can you explain the concept of channels in programming and their main purpose?

sobes.tech AI

Answer from AI

Channels in Go are a mechanism for transmitting data between goroutines (lightweight threads).

The main purpose of channels is to provide safe and synchronized communication between concurrent processes without using shared variables and locks.

Example of using a channel:

ch := make(chan int)

// Sending a value into the channel
go func() {
    ch <- 42
}()

// Receiving a value from the channel
value := <-ch
fmt.Println(value) // Will print 42

Channels allow writing simpler and safer concurrent programs.