这个使用range的方式有什么问题?

huangapple go评论102阅读模式
英文:

What's wrong with this usage of range?

问题

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

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

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

根据ReadDir的文档,它应该返回[]os.FileInfo作为第一个返回参数。然而,当我尝试编译它时,我得到了以下错误:

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

我错过了什么?

英文:

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?

答案1

得分: 6

这应该可以工作:

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

你忽略了索引,只赋值给了dir的条目。

如果你不想声明变量,也可以这样写:

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

注意在_, f后面的:=,而不是你的f =

问题不是来自ReadDir()返回的内容,而是来自range表达式,它返回(index, value)。

根据Go规范中的"For语句":

Range表达式                          第一个值          第二个值(如果第二个变量存在)

数组或切片  a  [n]E, *[n]E, or []E    索引    i  int    a[i]       E
英文:

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

huangapple
  • 本文由 发表于 2012年9月13日 19:07:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/12404875.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定