英文:
Go internal and pkg packages sharing same name
问题
我是你的中文翻译助手,以下是翻译好的内容:
我是一个 Go 的新手,一直在努力理解文件结构和包的最佳实践。
根据我所了解的,internal
文件夹包含不能被客户端使用的代码,而 pkg
文件夹包含可以被外部使用的代码。
假设我有一个资源,它有一些内部实现,同时也有一些可以被外部使用的函数。我应该在这两个文件夹下都创建同名的包,像这样吗?
- my-app
- pkg
- accounts
- accounts.go (包名为 accounts)
- internal
- accounts
- accounts.go (包名为 accounts)
然后在导入时,我需要指定 "app/my-app/internal/accounts"
或 "app/my-app/pkg/accounts"
,取决于我想要导入的模块?我该如何处理同名的内部和外部包?
英文:
I'm a go newbie and I've been struggling to understand the best practices when it comes to file structure and packages.
From what I've read, the internal
folder contains code that can't be consumed by clients and the pkg
folder contains code that could be used externally.
Say I have a resource that has some internal implementation and also has some functions that could be used externally. Would I just have packages with the same name under both folders like this?
- my-app
- pkg
- accounts
- accounts.go (package accounts)
- internal
- accounts
- accounts.go (package accounts)
and then when I import I specify "app/my-app/internal/accounts"
or "app/my-app/pkg/accounts"
depending on the module I want to import? How do I handle internal and external packages with the same name?
答案1
得分: 5
可以在除了internal
文件夹之外的任何文件夹中放置可外部导入的包。对于这些包,没有要求,也没有广泛认可的约定,要将它们放在pkg
文件夹中。
应用程序可以通过在导入规范中指定包名来解决同名包之间的冲突:
import (
iaccounts "my-app/internal/accounts"
accounts "my-app/accounts"
)
使用iaccounts
来引用内部包,使用accounts
来引用常规包。
英文:
Internal packages are described in the Go command documentation and this design document.
Externally importable packages can be in any folder except an internal
folder. There is no requirement nor is there a broadly agreed on convention that these packages should be in a pkg
folder.
Applications can resolve conflicts between packages with the same name by specifying a package name in the import specification:
import (
iaccounts "my-app/internal/accounts"
accounts "my-app/accounts"
)
Use iaccounts
to refer to the internal package and accounts
to refer to the regular package.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论