package main import ( "errors" "fmt" "math/rand" "time" ) // 模拟一个可能失败的操作 func mayFail() error { if rand.Float32() < 0.7 { // 70% 概率失败 return errors.New("something went wrong") } return nil } func main() { const maxAttempts = 3 attempt := 0 RETRY: // ← 标签:跳转点 attempt++ err := mayFail() if err != nil { fmt.Printf("attempt %d failed: %v\n", attempt, err) if attempt < maxAttempts { time.Sleep(time.Second) // 可选:做点延迟 goto RETRY // ← 关键:跳回标签 } fmt.Println("all attempts exhausted, giving up") return } fmt.Printf("success on attempt %d!\n", attempt) }