我最后的困境。如此简单的事情变得乏味。
我对 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} 因此数据在其中,但它是无法访问的。
提前致谢
回首忆惘然
相关分类