打印从0-10的平方,失败后重新执行

func main() {
    for i := 0; i < 10; i++ {
        ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*time.Duration(200))
        x := example(ctx, i)
        for x == -1 {
            ctx2, cancel2 := context.WithTimeout(context.Background(), time.Millisecond*time.Duration(200))
            x = example(ctx2, i)
            cancel2()
        }
        fmt.Println(x)
        cancel()
    }
}

func example(ctx context.Context, param int) int {
    rand.Seed(time.Now().Unix())

    select {
    case <-ctx.Done():
        // 超时
        return -1
    case <-time.After(time.Duration(rand.Intn(500)) * time.Millisecond):
        // 取消
        return param * param
    }
}

SyntaxError
199 声望20 粉丝