使用Go获取目录中文件的数量

How might I get the count of items returned by io/ioutil.ReadDir()?

I have this code, which works, but I have to think isn't the RightWay(tm) in Go.

package main

import "io/ioutil"
import "fmt"

func main() {
    files,_ := ioutil.ReadDir("/Users/dgolliher/Dropbox/INBOX")
    var count int
    for _, f := range files {
        fmt.Println(f.Name())
        count++
    }
    fmt.Println(count)
}

Lines 8-12 seem like way too much to go through to just count the results of ReadDir, but I can't find the correct syntax to get the count without iterating over the range. Help?

Dang it, figured it out right after I posted my question.

Found the answer in http://blog.golang.org/go-slices-usage-and-internals

package main

import "io/ioutil"
import "fmt"

func main() {
    files,_ := ioutil.ReadDir("/Users/dgolliher/Dropbox/INBOX")
    fmt.Println(len(files))
}

ReadDir returns a list of directory entries sorted by filename, so it is not just files. Here is a little function for those wanting to get a count of files only (and not dirs):

func fileCount(path string) (int, error){
    i := 0
    files, err := ioutil.ReadDir(path)
    if err != nil {
        return 0, err
    }
    for _, file := range files {
        if !file.IsDir() { 
            i++
        }
    }
    return i, nil
}

If you wanna get all files (not recursive) you can use len(files). If you need to just get the files without folders and hidden files just loop over them and increase a counter. And please don’t ignore errors