Junior — Middle
What are the ways to implement sequential execution of multiple goroutines with data transfer between them?
sobes.tech AI
Answer from AI
In Go, to execute multiple goroutines sequentially with data transfer between them, you can use the following methods:
- Channels — the main and most idiomatic way to transfer data between goroutines. You can create a channel through which one goroutine sends data, and the next receives and processes it, then passes it further.
ch1 := make(chan int)
ch2 := make(chan int)
// First goroutine
go func() {
ch1 <- 42 // send data
}()
// Second goroutine
go func() {
val := <-ch1 // receive data
ch2 <- val * 2
}()
// Main goroutine receives the result
result := <-ch2
fmt.Println(result) // 84
-
WaitGroup + channels — for controlling the completion of goroutines and sequence.
-
Passing data through closures or synchronized structures — less common, but possible.
-
Using context (context.Context) — for managing lifetime and cancellation, but not for direct data transfer.
Channels are the simplest and most reliable way to organize sequential processing with data transfer between goroutines.