首页 > 解决方案 > 在 Go 中递归遍历文件和文件夹 - 无法理解递归是如何发生的

问题描述

示例1.(我可以理解这段代码中的递归,findFactorial里面调用了函数)

package main

import "fmt"
var repeated = 0

func 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 times
Repeating.., Now repeated 2 times
Repeating.., Now repeated 3 times
Repeating.., Now repeated 4 times
Answer : 6

示例 2.(这里我无法理解,递归是如何发生的)

package main

import (
    "fmt"
    "log"
    "os"
    "path/filepath"
)
var repeated = 0
func 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.go
path ../../../../TEMP
Repeating.., Now repeated 1 times
File Name: TEMP
Repeating.., Now repeated 2 times
File Name: PNR.png
Repeating.., Now repeated 3 times
File Name: tkt.png
Repeating.., Now repeated 4 times
File Name: understand this.txt

标签: gorecursion

解决方案


第二个例子不是递归(至少从用户的角度来看)。您只需使用带有回调的 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)
    })
}


推荐阅读