Created
April 13, 2023 22:04
-
-
Save kitlabcode/7649b0abef9a864440aa0d396a0e5fa3 to your computer and use it in GitHub Desktop.
try function until
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
| // You can edit this code! | |
| // Click here and start typing. | |
| package main | |
| import ( | |
| "context" | |
| "fmt" | |
| "time" | |
| ) | |
| func tryFunc(ctx context.Context, f func() bool) bool { | |
| ticker := time.NewTicker(time.Second) | |
| defer ticker.Stop() | |
| for { | |
| select { | |
| case <-ctx.Done(): | |
| return false | |
| case <-ticker.C: | |
| if b := f(); b { | |
| return b | |
| } | |
| } | |
| } | |
| } | |
| func main() { | |
| ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) | |
| defer cancel() | |
| i := 0 | |
| outcome := tryFunc(ctx, func() bool { i++; return i == 2 }) | |
| fmt.Println(outcome) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment