这种范围的使用有什么问题?

时间:2012-09-13 11:07:19

标签: syntax go

我尝试使用此函数获取目录列表:

package main;
import ("fmt"; "os"; "io/ioutil")

func main() {
    dir, _ := ioutil.ReadDir("..")
    var f os.FileInfo
    for f = range dir {
        fmt.Println(f.Name())
    }
}

根据documentation of ReadDir,它应该返回[]os.FileInfo作为第一个返回参数。但是,当我尝试编译它时,我得到了

cannot assign type int to f (type os.FileInfo) in range: int does not implement os.FileInfo (missing IsDir method)

我错过了什么?

1 个答案:

答案 0 :(得分:6)

这应该有效:

for _, f = range dir {
        fmt.Println(f.Name())
    }

您忽略索引并仅分配目录条目。

如果您不想要,则不必声明var。这也可行:

func main() {
    dir, _ := ioutil.ReadDir("..")
    for _, f := range dir {
        fmt.Println(f.Name())
    }
}

请注意“:=”之后的“_, f”,而不是“f =”。

问题不是来自ReadDir()返回的内容,而是来自range表达式,它返回(索引,值)。
来自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
相关问题