英文:
Imports for Go package splitted into files
问题
如果我需要在Go语言中的两个或多个文件中为一个包导入同一个包,那么惯用的方式是什么?
直到今天,我是这样做的:
file1.go
package A
import "os"
file2.go
package A
import "os"
英文:
If I need an import in two or more files for one package in Go, what is the idiomatic way?
Until today I do it like this:
file1.go
package A
import "os"
file2.go
package A
import "os"
答案1
得分: 4
这不是一个关于是否符合习惯用法的问题,而是一个关于作用域的问题。
导入声明表示包含该声明的源文件依赖于导入包的功能(§程序初始化和执行),并且可以访问该包的导出标识符。
Go使用块进行词法作用域:
...
3. 导入包的包名的作用域是包含导入声明的文件块。
...
这意味着,如果有一个在多个文件中需要的包(无论是形成单个包还是多个包),你必须在所有这些文件中单独导入它。
你应该检查和修改如何在文件之间分离代码,因为这可能是一种将具有相同依赖关系(依赖于相同一组包)的函数和声明分组到同一个文件中的好方法,这样你只需要导入这些包一次。
还要注意,如果mypkg
包的某些文件依赖于一组其他包,但不依赖于mypkg
的其他文件,将mypkg
拆分为基于依赖关系的两个独立包也可能是有利的。大多数这些决策都是主观的,你需要判断它们在你的情况下是否合理。
英文:
It's not a question of being idiomatic, it's a question of scopes.
Import declarations are scoped to the containing file. Spec: Import declarations:
> An import declaration states that the source file containing the declaration depends on functionality of the imported package (§Program initialization and execution) and enables access to exported identifiers of that package.
Also Spec: Declarations and scope:
> Go is lexically scoped using blocks:
> ...
> 3. The scope of the package name of an imported package is the file block of the file containing the import declaration.
> ...
What this means is that if there's a package that is needed in multiple files (forming a single package or multiple, it doesn't matter), you have to import it separately in all of those files.
What you should do is review and revise how you separate code between files, because it may be a good way to group functions and declarations into the same file that have the same dependencies (that depend on the same set of packages), and so you would only need to import those packages once.
Also note that if certain files of package mypkg
depend on a set of other packages, but not the other files of mypkg
, it may also be profitable to split mypkg
into 2 separate packages based on the dependencies. Most of these decisions are subjective though, you have tell if they make sense in your case or not.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论