gpt4 book ai didi

syntax - 这种范围的用法有什么问题?

转载 作者:IT王子 更新时间:2023-10-29 01:25:30 28 4
gpt4 key购买 nike

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

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)

我错过了什么?

最佳答案

这应该有效:

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() 返回的内容,而是来自返回 (index, value) 的 range 表达式。
来自 Go 规范“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

关于syntax - 这种范围的用法有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12404875/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com