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

时间:2017-06-14 04:10:09

标签: function go wrapper

我尝试在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

任何人都可以帮我创建一个通用函数来包装函数来重试错误吗?

1 个答案:

答案 0 :(得分:1)

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

例如,更改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