GO语言规范-包

Go程序是通过把包链接到一起构成的。包是由一个个一起定义了属于该包的常量、类型、变量、函数(它们可以被同一个包内的所有文件访问,也可以通过导出而被其他的包使用)的源文件构成的。

源文件的组织结构

每个源文件都有一个package语句定义了它属于哪 个包,后面跟着可能为空的import集合声明了需要使用哪些包,再往后跟着可能为空的函数、类型、变量、常量的集合。

SourceFile = PackageClause “;” { ImportDecl “;” } { TopLevelDecl “;” } .

package 语句

每个源文件的开头必须是package 语句,指出它出属哪个包。

PackageClause = “package” PackageName .
PackageName = identifier .

其中的包名不能是空标识符。

package math

具有相同包名的文件构成了包的实现。不同的Go实现可要求所有的同一个包的源文件必须在同一个目录中。

import声明

源文件中的导入声明指出它依赖于所导入的包的功能(§Program initialization and execution) 并允许访问所导入包所导出的标识符。导入命名了一个标识符(包名)用于访问,以及一个导入路径来指定导入包所在位置。

ImportDecl = “import” ( ImportSpec | “(” { ImportSpec “;” } “)” ) .
ImportSpec = [ “.” | PackageName ] ImportPath .
ImportPath = string_lit .

其中包名用于在发起导入的源文件中修饰被导入包所导出的标识符。它的声明是文件范围内的。如果忽略了包名,那它的默认值就是被导入包的package语句所指定的标识符。如果使用点(.)来代替包名,则被导入包中所有导出的标识符都当成是在发起导入的源文件范围内声明的,不能使用修饰符来访问。

The interpretation of the ImportPath is implementation-dependent but it is typically a substring of the full file name of the compiled package and may be relative to a repository of installed packages.

Implementation restriction: A compiler may restrict ImportPaths to non-empty strings using only characters belonging to Unicode’s L, M, N, P, and S general categories (the Graphic characters without spaces) and may also exclude the characters !"#$%&’()*,:;<=>?[]^`{|} and the Unicode replacement character U+FFFD.

Assume we have compiled a package containing the package clause package math, which exports function Sin, and installed the compiled package in the file identified by “lib/math”. This table illustrates how Sin is accessed in files that import the package after the various types of import declaration.

Import declaration          Local name of Sin

import   "lib/math"         math.Sin
import m "lib/math"         m.Sin
import . "lib/math"         Sin

一个import声明也声明了发起导入方和被 导入方的依赖关系。包不可能引用自己,不论是直接的还是间接的,也不可以导入一个包却不使用它的导出标识符。如果只是为了让一个包初始化,请使用空标识符作为显式包名:

import _ “lib/math”

猜你喜欢

转载自blog.csdn.net/finalday/article/details/82796634