golang try 代码尝试执行
golang 官方没有 try
关键字做代码尝试执行,但 github 中有人为其做了个 try 功能的语法糖。
try 用法举例
package main
import (
"errors"
"fmt"
"github.com/matryer/try"
"math/rand"
"time"
)
func main() {
var value string
err := try.Do(func(attempt int) (bool, error) {
var err error
value, err = randomFunc()
if err != nil {
fmt.Println("run error:", err)
} else {
fmt.Println("run ok:", value)
}
return attempt < 5, err //设置尝试次数,即尝试 5 次
})
if err != nil {
fmt.Println("ERROR:", err)
}
}
func randomFunc() (string, error) {
rand_seed := rand.New(rand.NewSource(time.Now().UnixNano()))
if rand_seed.Intn(100) < 50 {
return "test ok", nil
} else {
return "", errors.New("test error")
}
}
代码解释:
- try 退出条件:1、达到尝试次数:5 次(默认+最高尝试次数是 10 次)\;或者 2、执行函数的返回值中 error 变量值为 nil。
golang-try 包源码解析
源码 list
package try
import "errors"
// MaxRetries is the maximum number of retries before bailing.
var MaxRetries = 10
var errMaxRetriesReached = errors.New("exceeded retry limit")
// Func represents functions that can be retried.
type Func func(attempt int) (retry bool, err error)
// Do keeps trying the function until the second argument
// returns false, or no error is returned.
func Do(fn Func) error {
var err error
var cont bool
attempt := 1
for {
cont, err = fn(attempt)
if !cont || err == nil {
break
}
attempt++
if attempt > MaxRetries {
return errMaxRetriesReached
}
}
return err
}
// IsMaxRetries checks whether the error is due to hitting the
// maximum number of retries or not.
func IsMaxRetries(err error) bool {
return err == errMaxRetriesReached
}
源码解析
- 从包源码结构中看,两个执行函数,
Do
和IsMaxRetries
。
Do
Do
的参数是类型为 func(attempt int) (retry bool, err error)
的函数指针,因此参数的定义格式必须满足 Func 自定义类的格式要求。该函数参数有两个返回值, retry
和 err
,这两个返回值是 try 是否退出尝试的关键标准, if !cont || err == nil
判定语句中标识,retry(即 cont)为 false 或 err 没有报错时,函数退出。因此在使用 try.Do 时,必须指定这两个变量。
次数控制由 Do 中 attempt
变量决定。attempt 每执行一次自动+1,并传入 Func 参数中,Func 参数根据指定的循环 try 次数,决定 retry 返回值是否为 true,当 true 时,则继续重试执行。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

上一篇: golang 参数传值
下一篇: MyBatis 介绍和使用
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论