Code Example: |
Example: Parallel Data Fetching with Goroutines and Channels
Suppose you want to fetch data from multiple APIs simultaneously. Using goroutines and channels lets you handle each API call concurrently.
package main
import (
"fmt"
"time"
)
func fetchData(source string, ch chan<- string) {
time.Sleep(2 * time.Second) // Simulate delay
ch <- fmt.Sprintf("Data from %s", source) // Send result to channel
}
func main() {
// Create a channel to receive data from goroutines
ch := make(chan string, 3)
sources := []string{"API1", "API2", "API3"}
for _, source := range sources {
go fetchData(source, ch) // Launch a goroutine for each API call
}
// Collect results from the channel
for range sources {
result := <-ch
fmt.Println(result)
}
}
|