英文:
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 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
.
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
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论