Junior — Middle
What is the preferred way to organize data transfer to goroutines: using channels or external variables?
sobes.tech AI
Answer from AI
In Go, it is preferable to pass data to goroutines through channels rather than external variables. This is because channels provide safe synchronization and data transfer between goroutines, preventing race conditions.
Using channels:
- Allows explicit control of data flow.
- Ensures blocking and synchronization.
- Improves code readability and maintainability.
Example of data transfer via channel:
ch := make(chan int)
// Sending data
go func() {
ch <- 42
}()
// Receiving data
val := <-ch
fmt.Println(val) // 42
Using external variables requires additional synchronization (e.g., with mutexes), which complicates the code and increases the risk of errors.
Therefore, it is recommended to use channels for data transfer between goroutines.