Home > Software engineering >  Go - What is the difference between "file block" & "package block"?
Go - What is the difference between "file block" & "package block"?

Time:03-29

Spec mentions that:

Each package has a package block containing all Go source text for that package.

Each file has a file block containing all Go source text in that file.


package block is the Go source text that starts with package clause

my understanding is every Go source text always start with package clause

How different is "file block" from "package block"?

CodePudding user response:

The obvious answer is that a file block contains the Go source text of a file, and the package block contains Go source text for a package. And a package is constructed from one or more source files.

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.

It's true that a package is always handled as one unit regardless of how the source code is "distributed" between its files, but there are constructs that are "file scoped". 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.

The most obvious is the import declarations. If a package consists of multiple files and you import another package in one file, you can't use that in another file (of the same package).

Another important construct is the Build constraints. A build constraint placed in a source file only applies to the given file and not to other files in the same package.

  •  Tags:  
  • go
  • Related