In the following code I am trying to add file information to a map, which gets added to a slice. The slice contains a map for every file on the filesystem. My understanding is this is similar to how you would build an array of dictionaries in Python.
package files
import (
"path/filepath"
"os"
"fmt"
)
func GetFiles() {
var numScanned int
var fileSlice = []map{}
numScanned = 0
var scan = func(path string, f os.FileInfo, err error) error {
numScanned ++
var fileDetails map[string]interface{}
fmt.Printf("%s with %d bytes
", path,f.Size())
fileDetails["filename"] = f.Name()
fileDetails["filesize"] = f.Size()
fileSlice = append(fileSlice, fileDetails) //Error = cannot use fileDetails (type map[string]interface {}) as type string in append
if err != nil {
fmt.Println(err)
} else {
fmt.Printf("%s with %d bytes
", path,f.Size())
}
return nil
}
directories := [] string {"C:\\"}
numOfDirectories := len(directories)
for i := 0; i < numOfDirectories; i++ {
err := filepath.Walk(directories[i], scan)
if err != nil {
fmt.Printf(err.Error())
}
}
fmt.Printf("%d", numScanned)
}
Error:
c:\project\src>go run main.go
# files
C:\project\src\files\files.go:12: syntax error: unexpected ]
C:\project\src\files\files.go:14: non-declaration statement outside function body
C:\project\src\files\files.go:36: non-declaration statement outside function body
C:\project\src\files\files.go:37: non-declaration statement outside function body
C:\project\src\files\files.go:44: non-declaration statement outside function body
C:\project\src\files\files.go:46: non-declaration statement outside function body
C:\project\src\files\files.go:48: syntax error: unexpected }
I'm also trying to work out how closures work in Go, so I can add file details to a map which is added to a slice, which I can access after filesystem.Walk has finished.
Thanks
EDIT:
I updated the code but how do you make a slice of map?