为了账号安全,请及时绑定邮箱和手机立即绑定

迭代结构类型的数组

迭代结构类型的数组

Go
白板的微信 2022-07-11 15:35:55
我最后的困境。如此简单的事情变得乏味。我对 Go 很陌生,我的目标是访问结构切片数组中的单个属性代码(文件 api.go):package apitype DirStruct struct {    dirName      string    dirPath      string    foldersCount int    filesCount   int}/*this function works*/func ListPathContent(path string) ([]*DirStruct, error) {    results := []*DirStruct{}    files, err := ioutil.ReadDir(path)    if err != nil {        log.Fatal(err)        return results, errors.New("Error -> get path " + path)    }    for _, f := range files {        if f.IsDir() {            dirPath := path + "\\" + f.Name()            filesCount := 0            foldersCount := 0            dircontent, _ := ioutil.ReadDir(dirPath)            for _, d := range dircontent {                if d.IsDir() {                    foldersCount++                } else {                    filesCount++                }            }            el := new(DirStruct)            el.dirName = f.Name()            el.dirPath = dirPath            el.foldersCount = foldersCount            el.filesCount = filesCount            results = append(results, el)        }    }    return results, nil代码(main.go)import //.... other pkgimport "./api"func main() {        ListPathContent, _ := api.ListPathContent("C:")            for _, p := range ListPathContent {        /* <--------- HERE'S the problem ---------> */        /* I can't do the the simplest and most obvious thing like this        fmt.Println(p.dirName) or fmt.Println(p.dirPath)        then the error is "p.dirName undefined (cannot refer to unexported field or method dirName)"                 */    }}当然,答案在我眼下,但是我不可能访问这些属性,如果我这样做fmt.Println(p),它将以JSON式格式返回所有结构,&{$WINDOWS.~BT C:\$WINDOWS.~BT 1 0} 因此数据在其中,但它是无法访问的。提前致谢
查看完整描述

1 回答

?
回首忆惘然

TA贡献1847条经验 获得超11个赞

如果包的名称以小写字母开头,则包中定义的所有标识符都是该包专用的。这称为未导出。此规则也适用于结构字段。


如果要从其他包中引用它们,则必须导出标识符。所以只需以大写字母开头他们的名字:


type DirStruct struct {

    DirName      string

    DirPath      string

    FoldersCount int

    FilesCount   int

}

规格:导出的标识符:

可以导出标识符以允许从另一个包访问它。如果同时满足以下条件,则导出标识符:

  1. 标识符名称的第一个字符是 Unicode 大写字母(Unicode 类“Lu”);和

  2. 标识符在包块中声明,或者是字段名方法名

不会导出所有其他标识符。

如果您不熟悉该语言,请先参加Go Tour基础知识:导出的名称中对此进行了介绍。


查看完整回答
反对 回复 2022-07-11
  • 1 回答
  • 0 关注
  • 113 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号