我有点困惑于这个递归类型定义:
type Func func() (int, int, Func)
注意:我知道如何通过试错来使用它,但我不确定它(递归类型定义(是什么
package main
import "fmt"
func fib(x int) int {
if x == 0 {
return 0
} else if x == 1 {
return 1
} else {
return fib(x-1) + fib(x-2)
}
}
type Func func() (int, int, Func)
func get_fib(x int) (int, int, Func) {
return x, fib(x), func() (int, int, Func) { return get_fib(x + 1) }
}
func main() {
d, n, f := get_fib(10)
d1, n1, f1 := f()
d2, n2, _ := f1()
fmt.Println(d, n)
fmt.Println(d1, n1)
fmt.Println(d2, n2)
}
有人能阐明上面递归类型定义中创建的内容吗?
类型Func func() (int, int, Func)
只是一个类型名称为Func
的函数类型。您可以将其视为一个参数为零、返回值为3的匿名函数(最后一个返回值也是Func类型(。
当将某个变量分配给该函数类型(Func
(时,该变量将是该函数的名称。然后可以调用以变量名作为函数名的函数。
在上面的代码中,d, n, f := get_fib(10)
,d得到10
,n得到fib(10)
,fu得到func() (int, int, Func) { return get_fib(11) }
。然后您可以调用f()
,它将直接返回get_fib(11)
的结果。
==============================================
为什么需要递归类型来创建此功能:
只是我的想法:get_fib函数想要返回三个结果:x,fib函数的输入(类型为int(,fib功能的结果(类型为整型(,一个返回get_fib(x+1(函数的函数(类型为func,现在不是func(。(所以get_fib也是一种递归,因为它在返回中使用get_fib。因此,函数的返回类型应该是int, int, func
(func是get_fib返回的第三个结果,也是函数定义本身(。因此需要一个递归函数类型。
简而言之:
- get_fib的输出为(int,int,customfunc(
- customfunc的输出是(get_fib(,它再次是(int,int,customfonc(
- 因此,customfunc的输出是(int,int,customfonc(,这是一个递归函数类型