Arun
Arun

Reputation: 1763

Loop through files and folders recursively in Go - Can't understand how recursion happening

Sample 1. ( I can understand recursion in this code, function findFactorial is called inside )

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 

}

Output

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

Sample 2. ( Here I am unable to understand, how recursion is happening )

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
    })
}

Output

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

Upvotes: 0

Views: 621

Answers (1)

Maxim Kosov
Maxim Kosov

Reputation: 1980

The second example is not a recursion (at least from a user perspective). You just use an API with a callback. filepath.Walk is a standard library function what takes a function as an argument. In this example the callback is a closure or anonymously defined function. That callback is called when filepath.Walk finds a new file system entry. Internally filepath.Walk may or may not be implemented as a recursion.

Just in case here's an example of using function as an argument that has nothing to do with a recursion:

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)
    })
}

Upvotes: 3

Related Questions