package main import ( "fmt" "time" ) func fetchData(dataChannel chan string, delay time.Duration) { // Simulate a network request or long-running operation time.Sleep(delay) dataChannel <- fmt.Sprintf("Data after %s delay", delay) } func main() { dataChan := make(chan string) // Scenario 1: Data arrives within timeout fmt.Println("--- Scenario 1: Data arrives within timeout ---") go fetchData(dataChan, time.Millisecond*500) select { case data := <-dataChan: fmt.Printf("Received: %s ", data) case <-time.After(time.Second * 1): fmt.Println("Timeout: No data received within 1 second.") } // Scenario 2: Data does not arrive within timeout fmt.Println(" --- Scenario 2: Data does not arrive within timeout ---") go fetchData(dataChan, time.Second * 2) select { case data := <-dataChan: fmt.Printf("Received: %s ", data) case <-time.After(time.Millisecond * 500): fmt.Println("Timeout: No data received within 500 milliseconds.") } // Ensure the goroutine from scenario 2 doesn't block main indefinitely // If fetchData was supposed to send to a different channel, we'd need to handle that. // Here, it will eventually send to dataChan, but main has moved on. time.Sleep(time.Second * 1) // Give it a moment to potentially print from the goroutine if it were still waiting. }