3

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?

2 Answers 2

8

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
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, very helpful. How is this called in Go? I assume 'callback' is wrong :-P
getWalkFunc is basically returning a closure. You can read more about them here: stackoverflow.com/documentation/go/2741/closures/9226/…
5

One way is by declaring loopThroughDirs anonymously inside main:

func main() {
    service, err := storage.New(client)
    ...
    filepath.Walk(*dirName, func(path string, fileInfo os.FileInfo, err error) error {
        ...do something with service...
        return nil
    })
}

1 Comment

Thank you, really helpful, but for this situation I'm going for the other answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.