Skip to content

Instantly share code, notes, and snippets.

@francoishill
Created August 1, 2014 16:52
Show Gist options
  • Star 37 You must be signed in to star a gist
  • Fork 10 You must be signed in to fork a gist
  • Save francoishill/a5aca2a7bd598ef5b563 to your computer and use it in GitHub Desktop.
Save francoishill/a5aca2a7bd598ef5b563 to your computer and use it in GitHub Desktop.
Loop through files and folders recursively in golang
package main
import (
"fmt"
"os"
"path/filepath"
)
func main() ([]string, error) {
searchDir := "c:/path/to/dir"
fileList := []string{}
err := filepath.Walk(searchDir, func(path string, f os.FileInfo, err error) error {
fileList = append(fileList, path)
return nil
})
for _, file := range fileList {
fmt.Println(file)
}
}
@hongwutian
Copy link

err decalared but not used

@bigUNO
Copy link

bigUNO commented Jun 12, 2017

@hongwutian Add _ = err to line 17 as a low budget work around.

@fiatjaf
Copy link

fiatjaf commented Jul 4, 2017

actually, you can just remove err := from line 13.

@farrellit
Copy link

wouldn't it be more prudent to handle the error?

@windoze95
Copy link

hmm, you're not going to be able to return in main function, nothing to return to :)

@elasti-eduardm
Copy link

tmp/sandbox198344374/main.go:9:6: func main must have no arguments and no return values
tmp/sandbox198344374/main.go:21:1: missing return at end of function

@fubarhouse
Copy link

Made some changes for consideration.

Changes include:

  • Handles error for Walk()
  • Walk returns errors as applicable
  • Changes variable declaration to use make()
  • Function has return value, including []string of files and error when applicable (expected nil)
  • Function should not be main with a return value, so it's now a separate function called from main.

You don't need to update this one, but I hope you consider it.

@0x113
Copy link

0x113 commented Oct 8, 2018

Thanks, very useful

Copy link

ghost commented Oct 12, 2018

@fubarhouse
no point in using make that I can see.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment