Middle+
How do you exchange data between goroutines?
sobes.tech AI
Answer from AI
In Go, data exchange between goroutines is usually done through channels. Channels provide safe and synchronized data transfer, allowing goroutines to communicate without explicit locks.
Example of using a channel for data transfer:
package main
import (
"fmt"
"time"
)
func worker(ch chan string) {
time.Sleep(time.Second)
ch <- "data from goroutine"
}
func main() {
ch := make(chan string)
go worker(ch)
msg := <-ch
fmt.Println(msg)
}
In this example, the main goroutine creates a channel ch and starts worker in a separate goroutine. worker sends a string to the channel, and the main goroutine receives it, synchronizing the exchange.
Besides channels, other mechanisms can be used, such as shared memory with synchronization via mutexes, but channels are considered a more idiomatic way in Go.