Go内部和pkg包具有相同的名称

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

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

内部包在Go命令文档这个设计文档中有描述。

可以在除了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.

huangapple
  • 本文由 发表于 2022年7月17日 05:06:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/73007657.html
匿名

发表评论

匿名网友

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

确定