登录
首页 >  Golang >  Go问答

对数组中的结构体类型进行迭代

来源:stackoverflow

时间:2024-03-02 16:00:29 388浏览 收藏

IT行业相对于一般传统行业,发展更新速度更快,一旦停止了学习,很快就会被行业所淘汰。所以我们需要踏踏实实的不断学习,精进自己的技术,尤其是初学者。今天golang学习网给大家整理了《对数组中的结构体类型进行迭代》,聊聊,我们一起来看看吧!

问题内容

我对 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} 所以数据在那里,但无法访问。


解决方案


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

如果您想从其他包中引用标识符,则必须导出标识符。因此,只需以大写字母开头即可:

type DirStruct struct {
    DirName      string
    DirPath      string
    FoldersCount int
    FilesCount   int
}

Spec: Exported identifiers:

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

  1. 标识符名称的第一个字符是 unicode 大写字母(unicode 类“lu”);和
  2. 标识符在 package block 中声明,或者是 field namemethod name

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

如果您不熟悉该语言,请先拨打 Go TourBasics: Exported names 中对此进行了介绍。

终于介绍完啦!小伙伴们,这篇关于《对数组中的结构体类型进行迭代》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>