Last active
November 1, 2022 15:53
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "context" | |
| "fmt" | |
| ) | |
| func gen(ctx context.Context) <-chan int { | |
| ch := make(chan int) | |
| go func() { | |
| var n int | |
| for { | |
| select { | |
| case <-ctx.Done(): | |
| return | |
| case ch <- n: | |
| n++ | |
| } | |
| } | |
| }() | |
| return ch | |
| } | |
| func main() { | |
| ctx, cancel := context.WithCancel(context.Background()) | |
| defer cancel() | |
| for n := range gen(ctx) { | |
| fmt.Println(n) | |
| if n == 5 { | |
| cancel() | |
| break | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@gerep It is duplicated I believe.
check the
exampleofWithCanceldoc: https://golang.org/pkg/context/#WithCancel