我最后的困境。如此简单的事情变得乏味。我对 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
}
可以导出标识符以允许从另一个包访问它。如果同时满足以下条件,则导出标识符:
不会导出所有其他标识符。
如果您不熟悉该语言,请先参加Go Tour。基础知识:导出的名称中对此进行了介绍。
- 1 回答
- 0 关注
- 113 浏览
添加回答
举报
0/150
提交
取消