0

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.

4
  • folder is not a package always. please specify packages in your file's in first line. Commented Sep 1, 2021 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. Commented Sep 1, 2021 at 15:05
  • 3
    The subfolder is a different package. Commented Sep 1, 2021 at 15:23
  • 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. Commented Sep 4, 2021 at 11:31

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.