Last active
November 1, 2022 15:53
-
-
Save rakyll/1aa860377dab8fd445431bbb3204f600 to your computer and use it in GitHub Desktop.
This file contains 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 | |
} | |
} | |
} |
Is it required to call cancel()
inside the n == 5
conditional even when you are using break
to escape the loop and using defer cancel()
?
@gerep It is duplicated I believe.
check the example
of WithCancel
doc: https://golang.org/pkg/context/#WithCancel
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@KyleHQ, looks like the process is more about handling passing channels over a number of functions (some of which may be third party) like when dealing with a HTTP request: https://blog.golang.org/context/google/google.go
Still looks like a standard
stop chan struct{}
would work, but thecontext
can also pass additional values all the way through so it combines a signaler + values.