Created
August 1, 2014 16:52
-
-
Save francoishill/a5aca2a7bd598ef5b563 to your computer and use it in GitHub Desktop.
Loop through files and folders recursively in golang
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 Add _ = err
to line 17 as a low budget work around.
actually, you can just remove err :=
from line 13.
wouldn't it be more prudent to handle the error?
hmm, you're not going to be able to return in main function, nothing to return to :)
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
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.
Thanks, very useful
@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
err decalared but not used