套件與匯入

最後更新


本頁說明 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 會在每組內依字母排序。
檔案樹:
  1. hello/
  2. ├── go.mod
  3. ├── main.go
  4. └── greet/
  5. ├── greet.go
  6. └── format/
  7. └── format.go

go.mod:
  1. module example.com/hello
  2. go 1.26

greet/format/format.go:
  1. package format
  2. import "strings"
  3. func Title(s string) string {
  4. if s == "" {
  5. return s
  6. }
  7. return strings.ToUpper(s[:1]) + s[1:]
  8. }

greet/greet.go:
  1. package greet
  2. import "example.com/hello/greet/format"
  3. func Hello(name string) string {
  4. return "Hello, " + format.Title(name)
  5. }

main.go:
  1. package main
  2. import (
  3. "fmt"
  4. "strings"
  5. "example.com/hello/greet"
  6. "example.com/hello/greet/format"
  7. )
  8. func main() {
  9. fmt.Println(greet.Hello("gopher"))
  10. fmt.Println(format.Title("go"))
  11. fmt.Println(strings.Repeat("=", 10))
  12. }

執行:
  1. $ go run .
  2. $ go list ./...

輸出:
  1. Hello, Gopher
  2. Go
  3. ==========
  4. example.com/hello
  5. example.com/hello/greet
  6. 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)。
  1. package main
  2. import (
  3. htmltemplate "html/template"
  4. "os"
  5. "text/template"
  6. )
  7. func main() {
  8. const src = "<p>{{.}}</p>\n"
  9. data := "<script>alert(1)</script>"
  10. t := template.Must(template.New("text").Parse(src))
  11. t.Execute(os.Stdout, data)
  12. h := htmltemplate.Must(htmltemplate.New("html").Parse(src))
  13. h.Execute(os.Stdout, data)
  14. }

輸出:
  1. <p><script>alert(1)</script></p>
  2. <p>&lt;script&gt;alert(1)&lt;/script&gt;</p>

空白匯入


有些套件被匯入時,會在 init 函式裡把自己「登記」到別的套件,之後就不必再直接呼叫它。典型例子:
  • _ "image/png":讓 image.Decode 認得 PNG 格式
  • _ "github.com/lib/pq" 這類資料庫驅動:讓 database/sql 能用該驅動開連線(見 database/sql)

但 Go 規定匯入了就必須用到,否則編譯失敗。空白匯入(blank import)就是在路徑前加底線 _,意思是「我只要它的初始化副作用,不會用它的名稱」。
下面自己做一個迷你的「驅動登記」機制:storage 套件保存一份驅動清單,memory 套件在 init 中登記自己,main 只用空白匯入載入 memory。
檔案樹:
  1. app/
  2. ├── go.mod
  3. ├── main.go
  4. └── storage/
  5. ├── storage.go
  6. └── memory/
  7. └── memory.go

go.mod:
  1. module example.com/app
  2. go 1.26

storage/storage.go:
  1. package storage
  2. import (
  3. "maps"
  4. "slices"
  5. )
  6. var drivers = map[string]func() string{}
  7. func Register(name string, open func() string) {
  8. drivers[name] = open
  9. }
  10. func Drivers() []string {
  11. return slices.Sorted(maps.Keys(drivers))
  12. }
  13. func Open(name string) (string, bool) {
  14. open, ok := drivers[name]
  15. if !ok {
  16. return "", false
  17. }
  18. return open(), true
  19. }

storage/memory/memory.go:
  1. package memory
  2. import "example.com/app/storage"
  3. func init() {
  4. storage.Register("memory", func() string {
  5. return "memory driver ready"
  6. })
  7. }

main.go:
  1. package main
  2. import (
  3. "fmt"
  4. "example.com/app/storage"
  5. _ "example.com/app/storage/memory"
  6. )
  7. func main() {
  8. fmt.Println("drivers:", storage.Drivers())
  9. msg, ok := storage.Open("memory")
  10. fmt.Println(msg, ok)
  11. _, ok = storage.Open("redis")
  12. fmt.Println("redis:", ok)
  13. }

執行:
  1. $ go run .

輸出:
  1. drivers: [memory]
  2. memory driver ready true
  3. redis: false

如果把 _ 拿掉,main.go 匯入了 memory 卻沒用到它的任何名稱,編譯會失敗:
  1. # example.com/app
  2. ./main.go:7:2: "example.com/app/storage/memory" imported and not used

注意:空白匯入的套件仍會完整編譯進程式,它的 init 一定會執行;不要為了「先留著以後用」而空白匯入。

internal 目錄


當專案變大,有些套件只想給自己用、不想讓外人匯入(避免別人依賴你隨時可能改動的內部細節)。Go 用目錄名稱 internal 做這件事,由編譯器強制執行:
路徑中含有 internal 的套件,只能被「internal 的上一層目錄」底下的程式碼匯入。

以下面的檔案樹為例:
套件誰可以匯入
example.com/shop/internal/configexample.com/shop 底下所有套件
example.com/shop/billing/internal/tax只有 example.com/shop/billing 與它的子目錄

其他 module 完全無法匯入 example.com/shop/internal/...。
檔案樹:
  1. shop/
  2. ├── go.mod
  3. ├── cmd/
  4. │ └── server/
  5. │ └── main.go
  6. ├── internal/
  7. │ └── config/
  8. │ └── config.go
  9. ├── billing/
  10. │ ├── billing.go
  11. │ └── internal/
  12. │ └── tax/
  13. │ └── tax.go
  14. └── report/
  15. └── report.go

go.mod:
  1. module example.com/shop
  2. go 1.26

internal/config/config.go:
  1. package config
  2. func Port() int {
  3. return 8080
  4. }

billing/internal/tax/tax.go:
  1. package tax
  2. func Rate() float64 {
  3. return 0.05
  4. }

billing/billing.go:
  1. package billing
  2. import "example.com/shop/billing/internal/tax"
  3. func Total(price float64) float64 {
  4. return price * (1 + tax.Rate())
  5. }

cmd/server/main.go:
  1. package main
  2. import (
  3. "fmt"
  4. "example.com/shop/billing"
  5. "example.com/shop/internal/config"
  6. )
  7. func main() {
  8. fmt.Println("port:", config.Port())
  9. fmt.Println("total:", billing.Total(100))
  10. }

report/report.go(試圖越界匯入 billing 的內部套件):
  1. package report
  2. import "example.com/shop/billing/internal/tax"
  3. func TaxRate() float64 {
  4. return tax.Rate()
  5. }

執行:
  1. $ go run ./cmd/server
  2. $ go build ./report

輸出:
  1. port: 8080
  2. total: 105
  3. package example.com/shop/report
  4. 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 目錄由編譯器強制限制:只有其上一層目錄底下的程式碼能匯入

資料來源