Multiple files in a directory are represented by the following structures:
type MyDirectory structure {
Name string
Files [ ] MyFile
}
type MyFile structure {
Name string
}
I want the MyFile
structure above to have a method to get a path that combines directory names and file names, but I got stuck in the "?"
section below.
func(f*MyFile) path()string{
return filepath.Join("?, f.Name)
}
What are the options?
go
Self-answer, Similar question.
How to have a child field have a pointer that references the parent.
type MyDirectory structure {
Name string
Files [ ] MyFile
}
type MyFile structure {
Dir* MyDirectory
Name string
}
func(f*MyFile) path()string {
return filepath.Join (f.Dir.Name, f.Name)
}
funcmain(){
d:=&MyDirectory {Name: "hoge"}
f:=MyFile {Dir:d,Name:"piyo.txt"}
d. Files=append(d.Files,f)
fmt.Println(f.path())//=>hoge/piyo.txt
d.Name="fuga"
fmt.Println(f.path())//=>fuga/piyo.txt
}
© 2024 OneMinuteCode. All rights reserved.