Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to construct an infinite tree directory by recursion in golang

Shulou Source: shulou.com Published: 2022-06-02 07:45:05 10月04日 Update

Golang how to use recursion to build an infinite tree directory, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain in detail for you, people with this need can come to learn, I hope you can gain something.

Package mainimport ("encoding/json"fmt"os"path/filepath"sort") func main () {rootpath: = "D:\\ projects" root: = FileNode {"projects", rootpath, [] * FileNode {}} fileInfo, _: = os.Lstat (rootpath) walk (rootpath, fileInfo, & root) data _: = json.Marshal (root) fmt.Printf ("% s", data)} type FileNode struct {Name string `json: "name" `Path string `json: "path" `FileNodes [] * FileNode `json: "children" `} func walk (path string, info os.FileInfo) Node * FileNode) {/ / list all directories and files under the current directory files: = listFiles (path) / / traverse these files for _, filename: = range files {/ / stitching full path fpath: = filepath.Join (path, filename) / / construct file structure fio _: = os.Lstat (fpath) / / add the current file as a child node to the directory child: = FileNode {filename, fpath, [] * FileNode {}} node.FileNodes = append (node.FileNodes, & child) / / if the current file traversing is a directory Enter the directory and recursively if fio.IsDir () {walk (fpath, fio, & child)}} return} func listFiles (dirname string) [] string {f, _: = os.Open (dirname) names _: = f.Readdirnames (- 1) f.Close () sort.Strings (names) return names} is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.

Tags: Directories documents recursion help clarity content for this articles beginners more knowledge structure nodes industry information information channels paths problems requirements channels Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi Shulou Tech Info Linux Xiaomi MariaDB