Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a variable in a Golang callback function?

Tags:

go

I have the following code:

func loopThroughDirs(path string, fileInfo os.FileInfo, err error) error {
    ...do something with service...
    return nil
}

func main() {
    service, err := storage.New(client)
    ...
    filepath.Walk(*dirName, loopThroughDirs)
}

The problem I want to solve is this, I want to use service inside loopThroughDirs(). How do I do this?

PS: Is the loopThroughDirs function inside filepath.Walk() called a callback in Go?

like image 638
Bob van Luijt Avatar asked Nov 20 '25 09:11

Bob van Luijt


1 Answers

You can also try returning a WalkFuncfunction :

func main() {
    service, err := storage.New(client)
    ...
    filepath.Walk(*dirName, getWalkFunc(service))
}

func getWalkFunc(service storage.Service) filepath.WalkFunc {
    return func(path string, fileInfo os.FileInfo, err error) error {
        // ...do something with service...
        return nil
    }
}
like image 89
abhink Avatar answered Nov 23 '25 02:11

abhink



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!