Why am I getting this error ? "err declared and not used"

package main

import (
    "fmt"
    "os"
	// "io/ioutil"
    "path/filepath"
)

func main() {
    searchDir := "target"

    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)
    }
}

It’s because you are assigning the error returned from filepath.Walk function to “err” and not doing anything with it. In Go all variables are bound to a type and a value, if you declare it, then you must use it otherwise the compiler will throw an error. The “err” here is an error type.

You should check the err for any returned errors like this:

err := filepath.Walk(searchDir, func(path string, f os.FileInfo, err error) error {
		fileList = append(fileList, path)
		return nil
	})
if err != nil {
log.Fatal("Error returned from filepath.Walk:", err)
}
5 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.