What's the idiomatic way, if possible, of having Go's filepath.Walk
return early?
I'm writing a function to find a nested directory of a given name. Using filepath.Walk
I can't see a way of terminating the tree-walking as soon as I find the first match.
func (*RecursiveFinder) Find(needle string, haystack string) (result string, err error) {
filepath.Walk(haystack, func(path string, fi os.FileInfo, errIn error) (errOut error) {
fmt.Println(path)
if fi.Name() == needle {
fmt.Println("Found " + path)
result = path
return nil
}
return
})
return
}
You should return an error from your walkfunc. To make sure no real error has been returned, you can just use a known error, like io.EOF
.
func Find(needle string, haystack string) (result string, err error) {
err = filepath.Walk(haystack,
filepath.WalkFunc(func(path string, fi os.FileInfo, errIn error) error {
fmt.Println(path)
if fi.Name() == needle {
fmt.Println("Found " + path)
result = path
return io.EOF
}
return nil
}))
if err == io.EOF {
err = nil
}
return
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With