我正在尝试使用GoLang创建一个迭代版本的程序,用于递归地编写。其目标是获取目录路径并返回一个JSON树,该树包含来自该目录的文件信息并保留目录结构。以下是我目前完成的内容:
我已创建了一个File结构体,用于包含目录树中每个条目的信息:
type File struct {
ModifiedTime time.Time `json:"ModifiedTime"`
IsLink bool `json:"IsLink"`
IsDir bool `json:"IsDir"`
LinksTo string `json:"LinksTo"`
Size int64 `json:"Size"`
Name string `json:"Name"`
Path string `json:"Path"`
Children []File `json:"Children"`
}
在我的迭代式程序中,我创建了一个栈以模拟递归调用。
func iterateJSON(path string) {
var stack []File
var child File
var file File
rootOSFile, _ := os.Stat(path)
rootFile := toFile(rootOSFile, path) //start with root file
stack = append(stack, rootFile) //append root to stack
for len(stack) > 0 { //until stack is empty,
file = stack[len(stack)-1] //pop entry from stack
stack = stack[:len(stack)-1]
children, _ := ioutil.ReadDir(file.Path) //get the children of entry
for i := 0; i < len(children); i++ { //for each child
child = (toFile(children[i], path+"/"+children[i].Name())) //turn it into a File object
file.Children = append(file.Children, child) //append it to the children of the current file popped
stack = append(stack, child) //append the child to the stack, so the same process can be run again
}
}
rootFile.Children
output, _ := json.MarshalIndent(rootFile, "", " ")
fmt.Println(string(output))
}
func toFile(file os.FileInfo, path string) File {
var isLink bool
var linksTo string
if file.Mode()&os.ModeSymlink == os.ModeSymlink {
isLink = true
linksTo, _ = filepath.EvalSymlinks(path + "/" + file.Name())
} else {
isLink = false
linksTo = ""
}
JSONFile := File{ModifiedTime: file.ModTime(),
IsDir: file.IsDir(),
IsLink: isLink,
LinksTo: linksTo,
Size: file.Size(),
Name: file.Name(),
Path: path,
Children: []File{}}
return JSONFile
}
理论上,随着我们遍历栈,子文件应该附加到根文件中。然而,唯一返回的是根文件(没有任何子文件被附加)。有什么想法为什么会发生这种情况吗?