I try to get a directory listing using this function:
package main;
import ("fmt"; "os"; "io/ioutil")
func main() {
dir, _ := ioutil.ReadDir("..")
var f os.FileInfo
for f = range dir {
fmt.Println(f.Name())
}
}
According to the documentation of ReadDir, it should return []os.FileInfo as the first return parameter. When I try to compile it, however, I get
cannot assign type int to f (type os.FileInfo) in range: int does not implement os.FileInfo (missing IsDir method)
What am I missing?
This should work:
You ignore the index and only assign the dir entry.
You don’t have to declare the var if you don’t want. This would also work:
Note the ‘
:=‘ after ‘_, f‘, instead of your ‘f =‘.The issue doesn’t comes from what
ReadDir()returns, but comes from therangeexpression, which returns (index, value).From the Go Specs “For Statements“: