示例1.(我可以理解这段代码中的递归,findFactorial里面调用了函数)package mainimport "fmt"var repeated = 0func main() { fmt.Println("Answer :",findFactorial(3))}func findFactorial(x int) int { repeated ++ fmt.Printf("Repeating.., Now repeated %v times\n",repeated) if x == 0 { return 1 } return x * findFactorial(x-1) // it is evident that this same function is calling again }输出go run .\factorial.go Repeating.., Now repeated 1 timesRepeating.., Now repeated 2 timesRepeating.., Now repeated 3 timesRepeating.., Now repeated 4 timesAnswer : 6示例 2.(这里我无法理解,递归是如何发生的)package mainimport ( "fmt" "log" "os" "path/filepath")var repeated = 0func main() { iterate("../../../../TEMP")}func iterate(path string) { fmt.Println("path",path) filepath.Walk(path, func(x string, info os.FileInfo, err error) error { repeated ++ fmt.Printf("Repeating.., Now repeated %v times\n",repeated) if err != nil { log.Fatalf(err.Error()) } fmt.Printf("File Name: %s\n", info.Name()) return nil })}输出go run .\filepathwalktu.gopath ../../../../TEMPRepeating.., Now repeated 1 timesFile Name: TEMPRepeating.., Now repeated 2 timesFile Name: PNR.pngRepeating.., Now repeated 3 timesFile Name: tkt.pngRepeating.., Now repeated 4 timesFile Name: understand this.txt
1 回答
慕田峪7331174
TA贡献1828条经验 获得超13个赞
第二个例子不是递归(至少从用户的角度来看)。您只需使用带有回调的 API。filepath.Walk是一个标准库函数,它将函数作为参数。在这个例子中,回调是一个闭包或匿名定义的函数。当filepath.Walk找到新的文件系统条目时调用该回调。在内部filepath.Walk可能会或可能不会实现为递归。
以防万一这是一个使用函数作为与递归无关的参数的示例:
func foo(cb func(int)) {
// cb is a function that passed as an argument
// it is called 3 times without any recursion
cb(0)
cb(1)
cb(2)
}
func main() {
foo(func(i int) {
fmt.Println("hello,", i)
})
}
- 1 回答
- 0 关注
- 84 浏览
添加回答
举报
0/150
提交
取消