套件與匯入
最後更新
本頁說明 Go 怎麼用匯入路徑找到套件,以及別名匯入、空白匯入與
internal 目錄這三個常見技巧。套件與匯入是什麼
套件(package)是 Go 組織程式碼的最小單位:同一個目錄裡的
.go 檔屬於同一個套件,共用同一個 package 名稱。要使用別的套件,就在檔案開頭用 import 把它「匯入」進來。可以把套件想成工具箱,匯入就是「把某個工具箱搬到桌上」。搬上桌後,只能拿到工具箱裡首字母大寫的工具(匯出的名稱,exported name);小寫開頭的是工具箱內部零件,外面拿不到。名稱可見範圍的細節見套件與作用域。
| 匯入寫法 | 用途 |
|---|---|
import "strings" | 一般匯入,用套件名稱 strings.X 取用 |
import tt "text/template" | 別名匯入,改用 tt.X 取用 |
import _ "image/png" | 空白匯入,只執行套件的初始化,不直接取用 |
匯入路徑
匯入路徑(import path)是一串用
/ 分隔的字串,告訴編譯器去哪裡找套件:- 標準庫套件直接寫名稱,例如
"fmt"、"net/http" - 自己專案裡的套件寫成「module 路徑 + 目錄」。module 路徑定義在
go.mod第一行(見 go.mod 與 Modules)
例如 module 叫
example.com/hello,那麼 greet/format 目錄的匯入路徑就是 example.com/hello/greet/format。程式裡用的是路徑最後一段的套件名稱 format,不是整串路徑。習慣上,標準庫放一組、自己與第三方套件放另一組,中間空一行;
gofmt 會在每組內依字母排序。檔案樹:
- hello/
- ├── go.mod
- ├── main.go
- └── greet/
- ├── greet.go
- └── format/
- └── format.go
go.mod:- module example.com/hello
- go 1.26
greet/format/format.go:- package format
- import "strings"
- func Title(s string) string {
- if s == "" {
- return s
- }
- return strings.ToUpper(s[:1]) + s[1:]
- }
greet/greet.go:- package greet
- import "example.com/hello/greet/format"
- func Hello(name string) string {
- return "Hello, " + format.Title(name)
- }
main.go:- package main
- import (
- "fmt"
- "strings"
- "example.com/hello/greet"
- "example.com/hello/greet/format"
- )
- func main() {
- fmt.Println(greet.Hello("gopher"))
- fmt.Println(format.Title("go"))
- fmt.Println(strings.Repeat("=", 10))
- }
執行:
- $ go run .
- $ go list ./...
輸出:
- Hello, Gopher
- Go
- ==========
- example.com/hello
- example.com/hello/greet
- example.com/hello/greet/format
go list ./... 列出 module 內所有套件的匯入路徑,忘記路徑怎麼寫時很好用。注意:Go 不允許套件互相匯入形成循環(A 匯入 B、B 又匯入 A),編譯會直接報
import cycle not allowed。匯入了卻沒用到的套件也會編譯失敗。別名匯入
兩個套件的名稱相同時(例如
text/template 與 html/template 都叫 template),同一個檔案無法同時用 template.X 指到兩者。這時在路徑前面加一個名字,就能替其中一個取別名(alias)。別名只在這個檔案內有效,不會影響其他檔案。除了解決撞名,別名也常用在名稱太長或容易和區域變數混淆的套件;沒有撞名時不必刻意取別名。
下面同時使用兩個
template 套件,可以看到 html/template 會自動跳脫 HTML 特殊字元,text/template 則原樣輸出(兩者的差異見 text/template 與 html/template)。- package main
- import (
- htmltemplate "html/template"
- "os"
- "text/template"
- )
- func main() {
- const src = "<p>{{.}}</p>\n"
- data := "<script>alert(1)</script>"
- t := template.Must(template.New("text").Parse(src))
- t.Execute(os.Stdout, data)
- h := htmltemplate.Must(htmltemplate.New("html").Parse(src))
- h.Execute(os.Stdout, data)
- }
輸出:
- <p><script>alert(1)</script></p>
- <p><script>alert(1)</script></p>
空白匯入
有些套件被匯入時,會在
init 函式裡把自己「登記」到別的套件,之後就不必再直接呼叫它。典型例子:_ "image/png":讓image.Decode認得 PNG 格式_ "github.com/lib/pq"這類資料庫驅動:讓database/sql能用該驅動開連線(見 database/sql)
但 Go 規定匯入了就必須用到,否則編譯失敗。空白匯入(blank import)就是在路徑前加底線
_,意思是「我只要它的初始化副作用,不會用它的名稱」。下面自己做一個迷你的「驅動登記」機制:
storage 套件保存一份驅動清單,memory 套件在 init 中登記自己,main 只用空白匯入載入 memory。檔案樹:
- app/
- ├── go.mod
- ├── main.go
- └── storage/
- ├── storage.go
- └── memory/
- └── memory.go
go.mod:- module example.com/app
- go 1.26
storage/storage.go:- package storage
- import (
- "maps"
- "slices"
- )
- var drivers = map[string]func() string{}
- func Register(name string, open func() string) {
- drivers[name] = open
- }
- func Drivers() []string {
- return slices.Sorted(maps.Keys(drivers))
- }
- func Open(name string) (string, bool) {
- open, ok := drivers[name]
- if !ok {
- return "", false
- }
- return open(), true
- }
storage/memory/memory.go:- package memory
- import "example.com/app/storage"
- func init() {
- storage.Register("memory", func() string {
- return "memory driver ready"
- })
- }
main.go:- package main
- import (
- "fmt"
- "example.com/app/storage"
- _ "example.com/app/storage/memory"
- )
- func main() {
- fmt.Println("drivers:", storage.Drivers())
- msg, ok := storage.Open("memory")
- fmt.Println(msg, ok)
- _, ok = storage.Open("redis")
- fmt.Println("redis:", ok)
- }
執行:
- $ go run .
輸出:
- drivers: [memory]
- memory driver ready true
- redis: false
如果把
_ 拿掉,main.go 匯入了 memory 卻沒用到它的任何名稱,編譯會失敗:- # example.com/app
- ./main.go:7:2: "example.com/app/storage/memory" imported and not used
注意:空白匯入的套件仍會完整編譯進程式,它的
init 一定會執行;不要為了「先留著以後用」而空白匯入。internal 目錄
當專案變大,有些套件只想給自己用、不想讓外人匯入(避免別人依賴你隨時可能改動的內部細節)。Go 用目錄名稱
internal 做這件事,由編譯器強制執行:路徑中含有internal的套件,只能被「internal的上一層目錄」底下的程式碼匯入。
以下面的檔案樹為例:
| 套件 | 誰可以匯入 |
|---|---|
example.com/shop/internal/config | example.com/shop 底下所有套件 |
example.com/shop/billing/internal/tax | 只有 example.com/shop/billing 與它的子目錄 |
其他 module 完全無法匯入
example.com/shop/internal/...。檔案樹:
- shop/
- ├── go.mod
- ├── cmd/
- │ └── server/
- │ └── main.go
- ├── internal/
- │ └── config/
- │ └── config.go
- ├── billing/
- │ ├── billing.go
- │ └── internal/
- │ └── tax/
- │ └── tax.go
- └── report/
- └── report.go
go.mod:- module example.com/shop
- go 1.26
internal/config/config.go:- package config
- func Port() int {
- return 8080
- }
billing/internal/tax/tax.go:- package tax
- func Rate() float64 {
- return 0.05
- }
billing/billing.go:- package billing
- import "example.com/shop/billing/internal/tax"
- func Total(price float64) float64 {
- return price * (1 + tax.Rate())
- }
cmd/server/main.go:- package main
- import (
- "fmt"
- "example.com/shop/billing"
- "example.com/shop/internal/config"
- )
- func main() {
- fmt.Println("port:", config.Port())
- fmt.Println("total:", billing.Total(100))
- }
report/report.go(試圖越界匯入 billing 的內部套件):- package report
- import "example.com/shop/billing/internal/tax"
- func TaxRate() float64 {
- return tax.Rate()
- }
執行:
- $ go run ./cmd/server
- $ go build ./report
輸出:
- port: 8080
- total: 105
- package example.com/shop/report
- report/report.go:3:8: use of internal package example.com/shop/billing/internal/tax not allowed
cmd/server 位在 shop/ 底下,所以能用 shop/internal/config;report 不在 billing/ 底下,所以碰不到 billing/internal/tax。重點整理
- 一個目錄就是一個套件;匯入路徑 = module 路徑 + 目錄,程式中用路徑最後一段的套件名稱取用
- 匯入卻沒使用、或套件互相循環匯入,都會編譯失敗
- 名稱撞在一起時用別名匯入,別名只在該檔案有效
_空白匯入只為了執行套件的init,常見於影像格式與資料庫驅動internal目錄由編譯器強制限制:只有其上一層目錄底下的程式碼能匯入