package main
import (
"context"
"fmt"
"time"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
result, err := performOperation(ctx)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("Result:", result)
}
func performOperation(ctx context.Context) (string, error) {
ch := make(chan string)
go func() {
time.Sleep(3 * time.Second)
ch <- "Operation completed successfully"
}()
select {
case result := <-ch:
return result, nil
case <-ctx.Done():
return "", ctx.Err()
}
}