1. package main
    2. import (
    3. "context"
    4. "fmt"
    5. "time"
    6. )
    7. func gen(ctx context.Context) <-chan int {
    8. ch := make(chan int)
    9. go func() {
    10. var n int
    11. for {
    12. select {
    13. case <-ctx.Done():
    14. break
    15. case ch <- n:
    16. n++
    17. // time.Sleep(time.Second)
    18. fmt.Println("n++")
    19. }
    20. }
    21. }()
    22. return ch
    23. }
    24. func main() {
    25. ctx, cancel := context.WithCancel(context.Background())
    26. defer cancel()
    27. for n := range gen(ctx) {
    28. time.Sleep(time.Second)
    29. if n == 5 {
    30. cancel()
    31. break
    32. }
    33. }
    34. }