Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to terminate early in Golang Walk?

Tags:

go

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
}
like image 495
EngineerBetter_DJ Avatar asked Apr 19 '16 08:04

EngineerBetter_DJ


1 Answers

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
}
like image 130
Not_a_Golfer Avatar answered Sep 19 '22 12:09

Not_a_Golfer