在同一个包但嵌套文件夹中,Go中的结构体不可见。

huangapple go评论82阅读模式
英文:

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

问题

我正在处理一个具有以下结构的Go项目:

pages(文件夹)
     -> faculty(文件夹)
        -> instructors.go 
        -> professors.go

     generalpages.go(在pages文件夹内)

generalpages.go 使用以下声明处理我的Repository模式结构:

type Repository struct {
	App *config.AppConfig
}

所有常见页面(例如"Home"、"About")都可以正常工作,具有这种类型的声明:

func (m *Repository) AboutPage(w http.ResponseWriter, r *http.Request) {
 // 一些功能
}

然而,如果我想要对我的InstructorsPage(在instructor.go内)使用相同的声明,如下所示,它就无法工作,VSCode中的错误显示为"undeclared name"。

在同一个包但嵌套文件夹中,Go中的结构体不可见。

我的理解是,对象应该在同一个包内可见,但它仍然无法工作。go build没有抛出任何错误,但当我使用一个路由包(chi)时,它无法正确引用它。

英文:

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.

在同一个包但嵌套文件夹中,Go中的结构体不可见。

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

得分: 3

Go语言的包不是这样工作的。

如果你的目录结构是:

moduleRootDir
  parentDir
     subDir

如果这两个目录都定义了包名为pkg,那么它们是两个不同的包。

如果模块名是module,那么parentDir中的包的导入路径是module/pkg,subDir中的包的导入路径是module/pkg/pkg。为了在parentDir的go文件中使用subDir中定义的名称,需要在其中导入它:

package pkg

import (
   subpkg "module/pkg/pkg"
)

然后可以使用subpkg.SymbolName来访问它们。

英文:

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.

huangapple
  • 本文由 发表于 2021年9月1日 22:52:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/69016124.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定