-2

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.

Patrick
  • 318
  • 3
  • 13
  • folder is not a package always. please specify packages in your file's in first line. – nipuna Sep 01 '21 at 15:02
  • the compiler will error if the package name is not specified in the first line. of course, the same package name is specified under the same folder. – Patrick Sep 01 '21 at 15:05
  • 3
    The subfolder is a different package. – Adrian Sep 01 '21 at 15:23
  • https://golang.org/ref/spec#Method_declarations `A receiver base type cannot be a pointer or interface type and it must be defined in the same package as the method.` –  Sep 04 '21 at 11:31

1 Answers1

4

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.

Burak Serdar
  • 46,455
  • 3
  • 40
  • 59