项目地址:https://github.com/fengyuan-liang/gofuture
go get "github.com/fengyuan-liang/gofuture"
futureFunc := future.FutureFunc[int](Fibonacci, 10)
result, err := futureFunc.Get()
// Fibonacci returns the nth Fibonacci number
func Fibonacci(n int) int {
if n <= 0 {
return 0
}
if n == 1 {
return 1
}
return Fibonacci(n-1) + Fibonacci(n-2)
}
或者这样,可以返回执行中可能出现的错误
futureFunc := future.FutureFunc[int](Add, 10, 20)
result, err := futureFunc.Get()
func Add(a, b int) (int, error) {
return a + b, errors.New("you can return error")
}
堵塞获取等待超时时间
futureFunc := FutureFunc[int](Fibonacci, 100) // This Fibonacci number is too large
result, err := futureFunc.GetWithTimeout(time.Second * 5)
当然也可以不使用匿名函数类型(显然匿名形式更加优雅)
futureFunc := FutureFunc[int](func() int {
return Fibonacci(100)
})