Go - struct not visible in the same package but nested folder

1.4k views Asked by At

I am working on a Go project with the structure as this:

pages (folder)
     -> faculty (folder)
        > instructors.go 
        > professors.go

     generalpages.go (inside pages folder)

generalpages.go handles my Repository pattern struct with the following declaration:

type Repository struct {
    App *config.AppConfig
}

All common pages (eg "Home", "About") works properly having this type of declaration:

func (m *Repository) AboutPage(w http.ResponseWriter, r *http.Request) {
 // some functionality
}

However, if I want to structure my pages and use the same declaration for my InstructorsPage (inside instructor.go) as follows, it doesn't work and the error in VSCode says: undeclared name.

My understanding is that an object should be visible within the same package, but still it doesn't work. go build is not throwing any error but when I use a routing package (chi), it can't reference it correctly.

1

There are 1 answers

0
Burak Serdar On

Go packages do not work that way.

If your directory structure is:

moduleRootDir
  parentDir
     subDir

and if both directory define the package name pkg, then these are two different packages.

If the module name is module, then the import path for the package in the parentDir is module/pkg, and the package in the subdir is module/pkg/pkg. In order to use the names defined in the subDir, import it in the go files in the parentDir:

package pkg

import (
   subpkg "module/pkg/pkg"
)

Then you can access them using subpkg.SymbolName.