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:
for _, f = range dir {
fmt.Println(f.Name())
}
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:
func main() {
dir, _ := ioutil.ReadDir("..")
for _, f := range dir {
fmt.Println(f.Name())
}
}
Note the ':=
' after '_, f
', instead of your 'f =
'.
The issue doesn't comes from what ReadDir()
returns, but comes from the range
expression, which returns (index, value).
From the Go Specs "For Statements":
Range expression 1st value 2nd value (if 2nd variable is present)
array or slice a [n]E, *[n]E, or []E index i int a[i] E