2013-09-29 45 views
1

我是golang的新手,并试图探索lang与示例业余爱好 项目,我需要编写下面的树状结构。 它就像文件系统一样,一个文件夹会有很多文件夹和文件。 树结构继续,直到它没有进一步的分支。golang树如Filesystem的解决方案

  [Fol] 

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

我的解决方法有:

type Fol struct{ 
    slice of Fol 
    slice of Fil 
} 

其服用时间为我设计的,因此,任何一次的帮助是非常赞赏。

问候, 比涅斯

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

回答

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)}}}