英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论