golang Tree喜欢Filesystem的解决方案

时间:2013-09-29 16:02:00

标签: go

我是golang的新手,并尝试用样本爱好来探索lang 项目我需要写下面的树状结构。 它像文件系统,一个文件夹将有许多文件夹和文件。 并且树结构继续,直到它没有进一步的分支。

          [Fol]

 [Fol,Fol,Fol] [Fil,Fil,Fil]

我的解决方案:

type Fol struct{
    slice of Fol
    slice of Fil
}

我花时间设计,所以任何曾经的帮助都非常感激。

此致 比涅斯

最后我使用了以下链接中提供的解决方案: https://stackoverflow.com/a/12659537/430294

1 个答案:

答案 0 :(得分:5)

这样的东西?

Playground link

package main

import "fmt"

type File struct {
    Name string
}

type Folder struct {
    Name    string
    Files   []File
    Folders []Folder
}

func main() {
    root := Folder{
        Name: "Root",
        Files: []File{
            {"One"},
            {"Two"},
        },
        Folders: []Folder{
            {
                Name: "Empty",
            },
        },
    }
    fmt.Printf("Root %#v\n", root)
}

打印

Root main.Folder{Name:"Root", Files:[]main.File{main.File{Name:"One"}, main.File{Name:"Two"}}, Folders:[]main.Folder{main.Folder{Name:"Empty", Files:[]main.File(nil), Folders:[]main.Folder(nil)}}}