How to Implement a Timeout with Channels and select

Implement a timeout in Go by using time.After with a select statement to handle completion or expiration.

Use time.After to create a timeout channel and select to wait for either the operation to complete or the timeout to expire.

package main

import (
	"fmt"
	"time"
)

func main() {
	result := make(chan string)
	
	go func() {
		time.Sleep(2 * time.Second)
		result <- "done"
	}()

	select {
	case res := <-result:
		fmt.Println("Success:", res)
	case <-time.After(1 * time.Second):
		fmt.Println("Timeout occurred")
	}
}