迭代结构类型的数组

我最后的困境。如此简单的事情变得乏味。


我对 Go 很陌生,我的目标是访问结构切片数组中的单个属性


代码(文件 api.go):


package api


type 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 pkg

import "./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} 因此数据在其中,但它是无法访问的。


提前致谢


白板的微信
浏览 114回答 1
1回答

回首忆惘然

如果包的名称以小写字母开头,则包中定义的所有标识符都是该包专用的。这称为未导出。此规则也适用于结构字段。如果要从其他包中引用它们,则必须导出标识符。所以只需以大写字母开头他们的名字:type DirStruct struct {&nbsp; &nbsp; DirName&nbsp; &nbsp; &nbsp; string&nbsp; &nbsp; DirPath&nbsp; &nbsp; &nbsp; string&nbsp; &nbsp; FoldersCount int&nbsp; &nbsp; FilesCount&nbsp; &nbsp;int}规格:导出的标识符:可以导出标识符以允许从另一个包访问它。如果同时满足以下条件,则导出标识符:标识符名称的第一个字符是 Unicode 大写字母(Unicode 类“Lu”);和标识符在包块中声明,或者是字段名或方法名。不会导出所有其他标识符。如果您不熟悉该语言,请先参加Go Tour。基础知识:导出的名称中对此进行了介绍。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go