1. 程式人生 > >GO語言規範-包

GO語言規範-包

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”