在 Go 中将函数作为参数传递

Pass function as argument in Go

我尝试在 Go 中创建一个函数,用于重试任何失败的查询函数(通常是因为序列化问题)。

func retryer(functionA func(interface{}) (interface{}, []error), maxRetry int, waitBetween time.Duration) interface{} {
    //when no error in functionA, retryer returns whatever functionA returns
    //when maxRetry is reached, returns nil
}

我想重试的功能如下所示

func GetTopStudent(classId string) ([]Student, []error) {
    //queries top 10 students for class with classId
}

func GetAverageStudentScores(classId string, from time.Time, until time.Time) ([]Pair, []error) {
    //queries all average score using aggregate, grouping by studentId
    //Pair behaves like C++ pair<string,string>
}

但是,结果是编译错误

cannot use GetTopStudent (type func(string) ([]Student, []error)) as type func(interface{}) (interface {}, []error) in argument to retryer

我试着稍微修改了一下,又遇到了一个编译错误

cannot use GetTopStudent (type func(string) ([]Student, []error)) as type func(string) (interface {}, []error) in argument to retryer

谁能帮我创建一个通用函数来包装一个错误重试的函数?

解决问题的更好方法是使用闭包。

例如,改变retryer的类型:

func retryer(f func() error, maxRetry int, waitBetween time.Duration) error {
    // retry and wait logic
    err := f()
    // error handling, retry, and wait logic
    return err
}

现在调用要重试的函数为:

// ...
classId := "some value"
// ...

var st []Student
var errors []error
err := retryer(func() error {
    st, errors = GetTopStudent(classId)
    // handle errors
    return nil
}, numTries, waitTime)
// use st here