Paulo Janeiro
Paulo Janeiro

Reputation: 3211

How to convert a type []os.FileInfo into a string?

I'm using this code to dynamically extract template filenames from a directory using this code:

files, _ := ioutil.ReadDir("./views")
    htmlFiles := ".html"
    for _, f := range files {
        if strings.Contains(files, htmlFiles) {
            fmt.Println(f.Name())
        }
    }

and I'm getting this error:

cannot use files (type []os.FileInfo) as type string in argument to strings.Contains

So, how to convert type []os.FileInfo into a string (or how do to this in a simpler way)?

Upvotes: 1

Views: 4213

Answers (1)

Mr_Pink
Mr_Pink

Reputation: 109404

The value returned by ioutil.ReadDir is a []os.FileInfo, which is a slice of interfaces. There's no general way to convert that into a meaningful string. You want to compare the name for each file individually:

files, err := ioutil.ReadDir("./views")
if err != nil {
    log.Fatal(err)
}

for _, f := range files {
    if strings.HasSuffix(f.Name(), ".html") {
        fmt.Println(f.Name())
    }
}

Upvotes: 5

Related Questions