I want to see the parent field from the child side method of the structure

Asked 2 years ago, Updated 2 years ago, 67 views

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

2022-09-30 16:17

1 Answers

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
}


2022-09-30 16:17

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.