Go - "file block" 和 "package block" 有什么区别?

Go - What is the difference between "file block" & "package block"?

Spec 提到:

每个包都有一个包块,其中包含该包的所有 Go 源文本。

每个文件都有一个包含该文件中所有 Go 源文本的文件块。


package 块是以 package 子句开头的 Go 源文本

我的理解是每个 Go 源文本总是以 package 子句开头

“文件块”与“包块”有何不同?

显而易见的答案是文件块包含文件的 Go 源文本,包块包含包的 Go 源文本。一个包是由一个或多个源文件构建的。

Spec: Packages:

Go programs are constructed by linking together packages. A package in turn is constructed from one or more source files that together declare constants, types, variables and functions belonging to the package and which are accessible in all files of the same package.

的确,无论源代码如何在其文件之间“分布”,包始终作为一个单元处理,但有些构造是“文件范围”的。 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.

最明显的是import declarations。如果一个包由多个文件组成,并且您在一个文件中导入另一个包,则不能在另一个文件(同一包的)中使用它。

另一个重要的结构是 Build constraints。源文件中的构建约束仅适用于给定文件,不适用于同一包中的其他文件。