Sobes.tech
Junior — Middle

How is interaction between goroutines in Go implemented?

sobes.tech AI

Answer from AI

In Go, interaction between goroutines is carried out using channels. Channels allow safe data transfer between goroutines and synchronization of their work.

Main points:

  • A channel is created with make(chan Type).
  • Sending to a channel: ch <- value.
  • Receiving from a channel: value := <-ch.
  • Channels can be buffered or unbuffered.

Example:

func main() {
    ch := make(chan string)

    go func() {
        ch <- "hello from goroutine"
    }()

    msg := <-ch
    fmt.Println(msg)
}

Thus, channels provide safe and convenient interaction between parallel goroutines without the need to use mutexes or other locking mechanisms.

How is interaction between goroutines in Go… - sobes.tech