How do import statements get resolved in multiple source files?

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

How do import statements get resolved in multiple source files?

问题

我一直在努力寻找这个问题的答案,但没有成功。

这个问题是关于在Go语言中,当一个包由多个源文件组成时的导入语句。

假设我有一个名为math的包,它由多个文件组成:

|-- math
   |-- add.go
   |-- subtract.go
   |-- divide.go
   |-- multiply.go

假设math包使用了fmt包,因此需要适当的导入语句。但是由于我们有四个单独的文件,我们必须多次导入fmt包(至少根据我的理解):

// add.go
import "fmt"

// subtract.go
import "fmt"

// divide.go
import "fmt"

// multiply.go
import "fmt"

现在的问题是,当包被编译时会发生什么?这些语句会被简单地合并在一起吗?

如果是这样,为什么我们需要多次导入包(每个文件一次),而不是只有一个文件包含所有的导入语句,以避免重复呢?

英文:

I've been trying to find an answer to this question without success.

The question is about import statements in Go when a package consists of multiple source files.

Let's say I have a package called math which consists of multiple files:

|-- math
   |-- add.go
   |-- subtract.go
   |-- divide.go
   |-- multiply.go

Let's assume that the math package makes use of the fmt package therefore it needs the appropriate import statement. But since we have four separate files, we have to import the fmt package multiple times (at least to my understanding):

// add.go
import "fmt"

// subtract.go
import "fmt"

// divide.go
import "fmt"

// multiply.go
import "fmt"

Now the question is, what happens when the package is compiled? Are the statements simply merged together?

If so, why do we have to import the package multiple times (once per each file) and not just have a single file with all the import statements so as to not repeat ourselves?

答案1

得分: 3

根据规范

导入包的包名的作用域是包含导入声明的文件块。

由于导入没有包作用域,导入不会合并在一起,并且在每个使用导入的文件中都需要导入。

导入的作用域与编译器和链接器加载导入的包的方式无关。这些工具足够智能,可以加载任何给定的包一次。

英文:

The specification says:

> The scope of the package name of an imported package is the file block of the file containing the import declaration.

Because imports do not have package scope, imports are not merged together and are required in each file that uses the import.

The scoping for imports is unrelated to how the compiler and linker load imported packages. These tools are smart enough to load any given package once.

huangapple
  • 本文由 发表于 2017年8月20日 07:08:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/45777038.html
匿名

发表评论

匿名网友

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

确定