Golang的文件系统树状解决方案

huangapple go评论87阅读模式
英文:

golang Tree like solution for Filesystem

问题

我是你的中文翻译助手,以下是翻译好的内容:

我是golang的新手,正在尝试通过一个简单的兴趣项目来探索这门语言。为此,我需要编写下面这种树形结构。它类似于文件系统,一个文件夹可以有多个文件夹和文件。树形结构会一直延伸下去,直到没有更多的分支。

我的解决方案是:

type Fol struct {
	folSlice []Fol
	filSlice []Fil
}

我在设计这个结构时花了些时间,所以非常感谢任何帮助。

祝好,
Vineeth

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

英文:

I am new to golang and trying to explore the lang with sample hobby
project for that I need to write the below tree like structure.
Its like File system, one Folder will have many Folder and files.
And tree structure goes on until it has no further branch.

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

My solution to have:

type Fol struct{
	slice of Fol
	slice of Fil
}

Its taking time for me to design, So any once help is very much appreciated.

Regards,
Vineeth

Finally I used solution provided in below link:
https://stackoverflow.com/a/12659537/430294

答案1

得分: 5

像这样吗?

Playground链接

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)}}}
英文:

Something like this?

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

Prints

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

huangapple
  • 本文由 发表于 2013年9月30日 00:01:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/19080116.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定