goto_labels.go 673 B

1234567891011121314151617181920212223242526272829303132333435
  1. package main
  2. import (
  3. "errors"
  4. "fmt"
  5. "math/rand"
  6. "time"
  7. )
  8. // 模拟一个可能失败的操作
  9. func mayFail() error {
  10. if rand.Float32() < 0.7 { // 70% 概率失败
  11. return errors.New("something went wrong")
  12. }
  13. return nil
  14. }
  15. func main() {
  16. const maxAttempts = 3
  17. attempt := 0
  18. RETRY: // ← 标签:跳转点
  19. attempt++
  20. err := mayFail()
  21. if err != nil {
  22. fmt.Printf("attempt %d failed: %v\n", attempt, err)
  23. if attempt < maxAttempts {
  24. time.Sleep(time.Second) // 可选:做点延迟
  25. goto RETRY // ← 关键:跳回标签
  26. }
  27. fmt.Println("all attempts exhausted, giving up")
  28. return
  29. }
  30. fmt.Printf("success on attempt %d!\n", attempt)
  31. }