Go 1.22

最後更新


Go 1.22 發布於 2024-02-06,目前最新修補版為 go1.22.12,已停止支援,請升級到 go1.27.4。

版本介紹


Go 1.22 修正了 Go 最常見的陷阱之一:for 迴圈變數改成「每次迭代都是新的變數」,在 goroutine 或閉包(closure)裡引用迴圈變數不再意外共用同一個值。同一版還能直接 for i := range 10、net/http 的路由支援 HTTP 方法與路徑參數,並推出標準庫第一個 v2 套件 math/rand/v2。升級時要注意:新的迴圈語意只對 go.mod 宣告 go 1.22 以上的模組生效,舊模組維持原行為;ServeMux 的新樣式語法可用 GODEBUG=httpmuxgo121=1 退回舊規則。

語言變更


  • for 迴圈宣告的變數每次迭代都會重新建立,詳見 for 與 range。
  • range 可以直接作用在整數上:for i := range n 會跑 0 到 n-1。
  • 以預覽方式提供函式迭代器(GOEXPERIMENT=rangefunc),於 Go 1.23 正式生效。

工具


  • 工作區可以用 go work vendor 建立 vendor 目錄,把所有相依放進專案。
  • go test -cover 對沒有測試檔的套件也會顯示 coverage: 0.0%,不再只寫 [no test files]。
  • go vet 新增檢查:append 沒有附加任何值、defer 裡直接呼叫 time.Since、log/slog 的鍵值參數不成對。
  • 執行追蹤(execution trace)全面改寫,負擔更低,go tool trace 介面也更新。
  • 在 GOPATH 模式(GO111MODULE=off)下不再支援 go get。

執行時與效能


  • GC 的型別資訊改放在每個堆積物件附近,CPU 效能提升 1–3%,多數程式記憶體負擔減少約 1%。
  • PGO 能去虛擬化更多呼叫,多數程式啟用後提升 2–14%。
  • 編譯器交錯執行去虛擬化與內聯,介面方法呼叫最佳化得更好。

標準庫重點


  • 新增 math/rand/v2:API 更一致,提供 ChaCha8、PCG 兩種產生器,詳見 math/rand/v2。
  • net/http.ServeMux 樣式可以寫 HTTP 方法與 {name} 路徑參數,用 Request.PathValue 取值,詳見 net/http。
  • slices.Concat 串接多個切片;cmp.Or 回傳第一個非零值的參數。
  • reflect.TypeFor[T]() 直接取得型別的 reflect.Type。
  • database/sql 新增泛型的 Null[T],表示可能為 NULL 的欄位。
  • 新增 go/version 套件,驗證與比較 go1.22.0 這類版本字串。

每次迭代一個新的迴圈變數


Go 1.22 以前,下面兩段都是經典陷阱:goroutine 讀到的 i、name 可能已經被迴圈改掉;閉包清單呼叫後全部印出 3。現在每次迭代都有自己的 i,結果符合直覺。
範例:
  1. package main
  2. import (
  3. "fmt"
  4. "sync"
  5. )
  6. func main() {
  7. var wg sync.WaitGroup
  8. results := make([]string, 3)
  9. for i, name := range []string{"a", "b", "c"} {
  10. wg.Add(1)
  11. go func() {
  12. defer wg.Done()
  13. results[i] = fmt.Sprintf("%d:%s", i, name)
  14. }()
  15. }
  16. wg.Wait()
  17. fmt.Println(results)
  18. var funcs []func() int
  19. for i := 0; i < 3; i++ {
  20. funcs = append(funcs, func() int { return i })
  21. }
  22. for _, f := range funcs {
  23. fmt.Print(f(), " ")
  24. }
  25. fmt.Println()
  26. }

輸出:
  1. [0:a 1:b 2:c]
  2. 0 1 2

注意:這個行為由模組 go.mod 的 go 版本決定;go 1.21 以下的模組即使用新工具鏈編譯,仍是舊的「整個迴圈共用一個變數」。

range 整數


只是要重複 n 次時,for i := range n 比 for i := 0; i < n; i++ 更短;不需要索引時寫 for range n。n 小於等於 0 時迴圈一次都不執行。
範例:
  1. package main
  2. import "fmt"
  3. func main() {
  4. for i := range 3 {
  5. fmt.Println("round", i)
  6. }
  7. total := 0
  8. for range 5 {
  9. total++
  10. }
  11. fmt.Println(total)
  12. }

輸出:
  1. round 0
  2. round 1
  3. round 2
  4. 5

增強的 ServeMux 路由


以前標準庫的路由只能比對路徑前綴,要分辨 GET/POST 或取出路徑中的 ID,多半得用第三方路由器。現在樣式可以寫成 "GET /users/{id}":方法不符時自動回 405 Method Not Allowed,{id} 用 r.PathValue("id") 取得。範例用 httptest 起一個本機伺服器。
範例:
  1. package main
  2. import (
  3. "fmt"
  4. "io"
  5. "net/http"
  6. "net/http/httptest"
  7. "strings"
  8. )
  9. func main() {
  10. mux := http.NewServeMux()
  11. mux.HandleFunc("GET /users/{id}", func(w http.ResponseWriter, r *http.Request) {
  12. fmt.Fprintf(w, "get user %s", r.PathValue("id"))
  13. })
  14. mux.HandleFunc("POST /users", func(w http.ResponseWriter, r *http.Request) {
  15. fmt.Fprint(w, "created")
  16. })
  17. srv := httptest.NewServer(mux)
  18. defer srv.Close()
  19. show := func(resp *http.Response, err error) {
  20. if err != nil {
  21. fmt.Println("error:", err)
  22. return
  23. }
  24. defer resp.Body.Close()
  25. body, _ := io.ReadAll(resp.Body)
  26. fmt.Println(resp.StatusCode, strings.TrimSpace(string(body)))
  27. }
  28. show(http.Get(srv.URL + "/users/42"))
  29. show(http.Post(srv.URL+"/users", "text/plain", nil))
  30. show(http.Post(srv.URL+"/users/42", "text/plain", nil))
  31. }

輸出:
  1. 200 get user 42
  2. 200 created
  3. 405 Method Not Allowed

math/rand/v2


rand.New(rand.NewPCG(1, 2)) 用固定種子建立產生器,每次執行結果相同,適合測試。方法名稱改得更一致,例如 Intn 改為 IntN;新的泛型函式 rand.N 可以產生任何整數型別(包含 time.Duration)的亂數。頂層函式使用自動隨機播種的全域產生器,不需要也不能手動設定種子。
範例:
  1. package main
  2. import (
  3. "fmt"
  4. "math/rand/v2"
  5. )
  6. func main() {
  7. r := rand.New(rand.NewPCG(1, 2))
  8. fmt.Println(r.IntN(100), r.IntN(100), r.IntN(100))
  9. fmt.Println(r.Float64() < 1)
  10. n := rand.N(10)
  11. fmt.Println(n >= 0 && n < 10)
  12. }

輸出:
  1. 76 61 78
  2. true
  3. true

本版新增的棄用 API


以下 API 從 Go 1.22 起標記為棄用(Deprecated),新程式不要再使用;說明欄為官方原文。
套件符號官方說明
go/astImporteruse the type checker [go/types] instead; see [Object].
go/astNewPackageuse the type checker [go/types] instead; see [Object].
go/astObjectThe relationship between Idents and Objects cannot be correctly computed without type information. For example, the expression T{K: 0} may denote a struct, map, slice, or array literal, depending on the type of T. If T is a struct, then K refers to a field of T, whereas for the other types it refers to a value in the environment.
go/astPackageuse the type checker [go/types] instead; see [Object].
go/astScopeuse the type checker [go/types] instead; see [Object].
html/templateErrJSTemplateErrJSTemplate is no longer returned when an action is present in a JS template literal. Actions inside of JS template literals are now escaped as expected.
reflectPtrToSuperseded by [PointerTo].

修補版本


版本發布日期含安全修補內容(官方原文)
go1.22.12024-03-05是includes security fixes to the crypto/x509, html/template, net/http, net/http/cookiejar, and net/mail packages, as well as bug fixes to the compiler, the go command, the runtime, the trace command, and the go/types and net/http packages.
go1.22.22024-04-03是includes a security fix to the net/http package, as well as bug fixes to the compiler, the go command, the linker, and the encoding/gob, go/types, net/http, and runtime/trace packages.
go1.22.32024-05-07是includes security fixes to the go command and the net package, as well as bug fixes to the compiler, the runtime, and the net/http package.
go1.22.42024-06-04是includes security fixes to the archive/zip and net/netip packages, as well as bug fixes to the compiler, the go command, the linker, the runtime, and the os package.
go1.22.52024-07-02是includes security fixes to the net/http package, as well as bug fixes to the compiler, cgo, the go command, the linker, the runtime, and the crypto/tls, go/types, net, net/http, and os/exec packages.
go1.22.62024-08-06否includes fixes to the go command, the compiler, the linker, the trace command, the covdata command, and the bytes, go/types, and os/exec packages.
go1.22.72024-09-05是includes security fixes to the encoding/gob, go/build/constraint, and go/parser packages, as well as bug fixes to the fix command and the runtime.
go1.22.82024-10-01否includes fixes to cgo, and the maps and syscall packages.
go1.22.92024-11-06否includes fixes to the linker.
go1.22.102024-12-03否includes fixes to the runtime and the syscall package.
go1.22.112025-01-16是includes security fixes to the crypto/x509 and net/http packages, as well as bug fixes to the runtime.
go1.22.122025-02-04是includes security fixes to the crypto/elliptic package, as well as bug fixes to the compiler and the go command.

已知漏洞


在 Go 1.22 系列修補版中修正的漏洞共 17 個;仍影響最新修補版 go1.22.12 的漏洞共 97 個。

本系列已修正


編號CVE摘要(官方原文)修正於
GO-2025-3447CVE-2025-22866Timing sidechannel for P-256 on ppc64le in crypto/internal/nistecgo1.22.12、go1.23.6、go1.24.0-rc.3
GO-2025-3420CVE-2024-45336Sensitive headers incorrectly sent after cross-domain redirect in net/httpgo1.22.11、go1.23.5、go1.24.0-rc.2
GO-2025-3373CVE-2024-45341Usage of IPv6 zone IDs can bypass URI name constraints in crypto/x509go1.22.11、go1.23.5、go1.24.0-rc.2
GO-2024-3107CVE-2024-34158Stack exhaustion in Parse in go/build/constraintgo1.22.7、go1.23.1
GO-2024-3106CVE-2024-34156Stack exhaustion in Decoder.Decode in encoding/gobgo1.22.7、go1.23.1
GO-2024-3105CVE-2024-34155Stack exhaustion in all Parse functions in go/parsergo1.22.7、go1.23.1
GO-2024-2963CVE-2024-24791Denial of service due to improper 100-continue handling in net/httpgo1.21.12、go1.22.5
GO-2024-2888CVE-2024-24789Mishandling of corrupt central directory record in archive/zipgo1.21.11、go1.22.4
GO-2024-2887CVE-2024-24790Unexpected behavior from Is methods for IPv4-mapped IPv6 addresses in net/netipgo1.21.11、go1.22.4
GO-2024-2825CVE-2024-24787Arbitrary code execution during build on Darwin in cmd/gogo1.21.10、go1.22.3
GO-2024-2824CVE-2024-24788Malformed DNS message can cause infinite loop in netgo1.22.3
GO-2024-2687CVE-2023-45288HTTP/2 CONTINUATION flood in net/httpgo1.21.9、go1.22.2
GO-2024-2610CVE-2024-24785Errors returned from JSON marshaling may break template escaping in html/templatego1.21.8、go1.22.1
GO-2024-2609CVE-2024-24784Comments in display names are incorrectly handled in net/mailgo1.21.8、go1.22.1
GO-2024-2600CVE-2023-45289Incorrect forwarding of sensitive headers and cookies on HTTP redirect in net/httpgo1.21.8、go1.22.1
GO-2024-2599CVE-2023-45290Memory exhaustion in multipart form parsing in net/textproto and net/httpgo1.21.8、go1.22.1
GO-2024-2598CVE-2024-24783Verify panics on certificates with an unknown public key algorithm in crypto/x509go1.21.8、go1.22.1

本版已停止支援,不會再修正這些漏洞;完整清單見 資安漏洞。

資料來源