Go 1.27

最後更新


Go 1.27 發布於 2026-08-19,目前最新修補版為 go1.27.4,仍在支援期。

版本介紹


Go 1.27 帶來泛型推出以來最受期待的語言功能:方法也能宣告自己的型別參數(泛型方法),不必再把這類函式寫成套件層級的函式。標準庫方面,encoding/json/v2 結束實驗正式推出,原本的 encoding/json 也改由 v2 實作支撐,解碼明顯變快;另外新增 uuid 與後量子簽章 crypto/mldsa 套件。升級時要注意:Go 1.27 需要 macOS 13 以上;asynctimerchan 等多個 GODEBUG 設定已永久移除,計時器通道一律無緩衝;encoding/json 的錯誤訊息文字可能與以前不同,依賴錯誤字串比對的程式需要調整,必要時可用 GOEXPERIMENT=nojsonv2 暫時退回舊實作。

語言變更


  • 方法宣告可以有自己的型別參數,例如 func (l List[T]) Map[U any](f func(T) U) List[U],詳見 泛型函式。
  • 介面的方法不能宣告型別參數,泛型方法也不能用來實作介面方法。
  • 結構字面值(struct literal)的鍵可以是任何有效的欄位選擇器,例如直接寫嵌入欄位提升上來的欄位名稱。
  • 把泛型函式指派給(或轉換成)函式型別的變數時,型別推斷在所有情境都適用。

工具


  • go test 預設執行 stdversion 檢查,回報使用了比 go.mod 版本更新的標準庫符號。
  • go doc 支援 pkg@version 語法,新增 -ex 列出可執行範例並能印出範例原始碼。
  • go fix 新增 atomictypes、embedlit、slicesbackward、unsafefuncs 等現代化修正器。
  • go.mod 宣告 go 1.27 以上時,go mod tidy 會把分散的 require 區塊合併成「直接相依」與「間接相依」兩塊。
  • go vet 的 printf 檢查會回報用 %w 包裝「指向錯誤型別的指標」這種常見隱藏錯誤。
  • go 指令不再支援 Bazaar(bzr)版本控制系統。
  • gofmt 修正欄位對齊邏輯,重新格式化舊程式碼時可能出現少量空白差異。

執行時與效能


  • 編譯器改呼叫依大小特化的記憶體配置函式,部分小於 80 位元組的配置最多快 30%,執行檔約增加 60 KB。
  • goroutine 洩漏剖析正式推出:runtime/pprof 的 goroutineleak 剖析,以及 net/http/pprof 的 /debug/pprof/goroutineleak 端點,詳見 pprof。
  • go 1.27 以上的模組,panic 的堆疊追蹤會在標頭印出 goroutine 標籤,可用 GODEBUG=tracebacklabels=0 關閉。
  • asynctimerchan GODEBUG 永久移除,time 套件建立的通道一律無緩衝。
  • 編譯器為閉包產生更簡短、與內聯無關的名稱。

標準庫重點


  • encoding/json/v2 與 encoding/json/jsontext 正式推出;v1 的 API 繼續支援,不強制遷移,詳見 encoding/json。
  • 新增 uuid 套件,產生與解析 UUID。
  • 新增 crypto/mldsa,實作 FIPS 204 的後量子簽章 ML-DSA;crypto/x509 與 crypto/tls 同步支援。
  • strings.CutLast、bytes.CutLast 在「最後一次」出現分隔符號處切開。
  • math/rand/v2 的 Rand 新增泛型方法 N;math/big.Int 新增 Divide,可選擇捨入模式。
  • net/http 的 HTTP/1 Response.Body 關閉時會自動讀完少量未讀內容,提高連線重用率;HTTP/2 伺服器支援 RFC 9218 優先順序。
  • net/http/httptest.NewTestServer 建立搭配 testing/synctest 的記憶體內伺服器;synctest.Sleep 結合 time.Sleep 與 synctest.Wait。
  • net/url 新增 URL.Clone 與 Values.Clone;Unicode 資料升級到 17 版。
  • 新增實驗性的可攜式 simd 套件(GOEXPERIMENT=simd),simd/archsimd 增加 arm64 與 WebAssembly 支援。

泛型方法


以前方法不能有自己的型別參數,像「把 List[int] 轉成 List[string]」只能寫成套件函式 Map(list, f)。現在方法可以在名稱後面加 [U any],寫成 nums.Map(f),呼叫時型別參數一樣能自動推斷。非泛型型別也能有泛型方法,如下面的 Bag.Format。
範例:
  1. package main
  2. import (
  3. "fmt"
  4. "strconv"
  5. )
  6. type List[T any] struct {
  7. items []T
  8. }
  9. func (l List[T]) Map[U any](f func(T) U) List[U] {
  10. out := List[U]{}
  11. for _, v := range l.items {
  12. out.items = append(out.items, f(v))
  13. }
  14. return out
  15. }
  16. type Bag struct {
  17. values []int
  18. }
  19. func (b Bag) Format[S ~string](prefix S) []S {
  20. var out []S
  21. for _, v := range b.values {
  22. out = append(out, prefix+S(strconv.Itoa(v)))
  23. }
  24. return out
  25. }
  26. func main() {
  27. nums := List[int]{items: []int{1, 2, 3}}
  28. strs := nums.Map(func(n int) string { return fmt.Sprintf("<%d>", n) })
  29. fmt.Println(strs.items)
  30. type Label string
  31. fmt.Println(Bag{values: []int{7, 8}}.Format(Label("id-")))
  32. }

輸出:
  1. [<1> <2> <3>]
  2. [id-7 id-8]

注意:泛型方法不能拿來滿足介面;介面裡的方法也不能宣告型別參數。

結構字面值使用提升欄位


嵌入(embedding)的結構,其欄位會被「提升」到外層,可以直接用 u.ID 存取,但以前建立時必須寫成 User{Base: Base{ID: 1}}。現在字面值的鍵可以直接寫提升欄位 ID、Kind,讀寫寫法一致。詳見 嵌入。
範例:
  1. package main
  2. import "fmt"
  3. type Base struct {
  4. ID int
  5. Kind string
  6. }
  7. type User struct {
  8. Base
  9. Name string
  10. }
  11. func main() {
  12. u := User{ID: 1, Kind: "admin", Name: "gopher"}
  13. fmt.Printf("%+v\n", u)
  14. }

輸出:
  1. {Base:{ID:1 Kind:admin} Name:gopher}

encoding/json/v2


v2 的 Marshal、Unmarshal 都接受選項參數,預設比 v1 更嚴格:重複的鍵、無效的 UTF-8 會回傳錯誤。RejectUnknownMembers(true) 拒絕結構中沒有的欄位,適合嚴格驗證 API 輸入;Deterministic(true) 讓相同輸入一定得到相同輸出。Go 1.27 起不需要再設定 GOEXPERIMENT。
範例:
  1. package main
  2. import (
  3. "encoding/json/v2"
  4. "fmt"
  5. )
  6. type Config struct {
  7. Host string `json:"host"`
  8. Port int `json:"port"`
  9. }
  10. func main() {
  11. var c Config
  12. err := json.Unmarshal([]byte(`{"host":"localhost","port":8080}`), &c)
  13. fmt.Println(c, err)
  14. err = json.Unmarshal([]byte(`{"host":"a","host":"b"}`), &c)
  15. fmt.Println(err)
  16. err = json.Unmarshal([]byte(`{"host":"a","debug":true}`), &c, json.RejectUnknownMembers(true))
  17. fmt.Println(err)
  18. out, _ := json.Marshal(map[string]int{"b": 2, "a": 1}, json.Deterministic(true))
  19. fmt.Println(string(out))
  20. }

輸出:
  1. {localhost 8080} <nil>
  2. jsontext: duplicate object member name "host"
  3. json: cannot unmarshal JSON string into Go main.Config: unknown object member name "debug"
  4. {"a":1,"b":2}

uuid


UUID 是 128 位元的唯一識別碼,以前需要第三方套件。uuid.Parse 解析字串(不分大小寫),失敗時回傳錯誤;uuid.New 產生隨機的第 4 版;uuid.NewV7 產生含時間戳記、依建立順序遞增的第 7 版,適合當資料庫主鍵。UUID 是 16 位元組陣列,可以直接用 == 比較。範例中隨機產生的值每次不同,所以只印長度與比較結果。
範例:
  1. package main
  2. import (
  3. "fmt"
  4. "uuid"
  5. )
  6. func main() {
  7. id, err := uuid.Parse("f47ac10b-58cc-4372-a567-0e02b2c3d479")
  8. if err != nil {
  9. fmt.Println("error:", err)
  10. return
  11. }
  12. fmt.Println(id)
  13. fmt.Println(id == uuid.MustParse("F47AC10B-58CC-4372-A567-0E02B2C3D479"))
  14. a := uuid.NewV7()
  15. b := uuid.NewV7()
  16. fmt.Println(len(a.String()), a.Compare(b) < 0, a != uuid.Nil())
  17. _, err = uuid.Parse("not-a-uuid")
  18. fmt.Println(err)
  19. }

輸出:
  1. f47ac10b-58cc-4372-a567-0e02b2c3d479
  2. true
  3. 36 true true
  4. invalid uuid

strings.CutLast 與 Rand.N 方法


strings.CutLast 在最後一個分隔符號處切開,適合取出副檔名或檔名,取代 LastIndex 再自己切片的寫法。math/rand/v2 的 Rand 現在也有泛型方法 N,和頂層的 rand.N 一樣能產生 time.Duration 等任何整數型別的亂數。
範例:
  1. package main
  2. import (
  3. "fmt"
  4. "math/rand/v2"
  5. "strings"
  6. "time"
  7. )
  8. func main() {
  9. dir, file, found := strings.CutLast("/var/log/app/server.log", "/")
  10. fmt.Println(dir, file, found)
  11. name, ext, _ := strings.CutLast("archive.tar.gz", ".")
  12. fmt.Println(name, ext)
  13. r := rand.New(rand.NewPCG(1, 2))
  14. d := r.N(10 * time.Second)
  15. fmt.Println(d >= 0 && d < 10*time.Second)
  16. }

輸出:
  1. /var/log/app server.log true
  2. archive.tar gz
  3. true

本版新增的棄用 API


以下 API 從 Go 1.27 起標記為棄用(Deprecated),新程式不要再使用;說明欄為官方原文。
套件符號官方說明
crypto/tlsConfig.Randthis should be left nil in production. Not all TLS configurations are guaranteed to use Rand. Test code can use [testing/cryptotest.SetGlobalRandom] instead.

修補版本


版本發布日期含安全修補內容(官方原文)
go1.27.12026-09-01否includes fixes to cgo, the compiler, the runtime, the go fix command, and the database/sql, debug/elf, encoding/json, net/http, os, simd, and simd/archsimd packages.
go1.27.22026-10-08是includes security fixes to the go command, and the crypto/tls, html/template, net/http, net/textproto, and os packages, as well as bug fixes to the compiler, the linker, the runtime, the cover tool, the go fix command, vet, and the compress/flate, crypto/mlkem, encoding/json, encoding/json/v2, net/http, and os packages.
go1.27.32026-10-19是includes security fixes to the crypto/x509 package.
go1.27.42026-11-10是includes security fixes to cgo, the go command, the compiler, the linker, and the net/http package, as well as bug fixes to the assembler, the compiler, the runtime, toolchain bootstrapping, and the crypto/fips140, crypto/hkdf, crypto/rsa, crypto/tls, and net packages.

已知漏洞


在 Go 1.27 系列修補版中修正的漏洞共 45 個;仍影響最新修補版 go1.27.4 的漏洞共 0 個。

本系列已修正


編號CVE摘要(官方原文)修正於
GO-2026-6859CVE-2026-97054HTTP/1 server crash due to MaxBytesReader header race in net/httpgo1.26.11、go1.27.4
GO-2026-6858CVE-2026-97033Unexpected code execution via --sysroot, -target, -isysroot, -Wl,-syslibroot, and -x cgo flags in cmd/gogo1.26.11、go1.27.4
GO-2026-6857CVE-2026-97034Arbitrary command execution via GCC spec files in cgo linker search directories in cmd/gogo1.26.11、go1.27.4
GO-2026-6856CVE-2026-97035Unexpected code execution and arbitrary file write via Clang -gen-* and GCC -gnat* flags in cgo in cmd/gogo1.26.11、go1.27.4
GO-2026-6855CVE-2026-97036Arbitrary code execution during build on darwin via "-l to_library" in cgo in cmd/gogo1.26.11、go1.27.4
GO-2026-6854CVE-2026-97037Linker script injection via split -Wl, flags and Darwin or symbol linker flags in cgo in cmd/gogo1.26.11、go1.27.4
GO-2026-6853CVE-2026-97038Arbitrary code execution via crafted .syso files and cgo linker input files in cmd/gogo1.26.11、go1.27.4
GO-2026-6852CVE-2026-97039Flag sanitization bypass via "#cgo pkg-config:" directives in cmd/gogo1.26.11、go1.27.4
GO-2026-6851CVE-2026-97040Cgo directive injection via .syso files disguised as Go object files in cmd/go and cmd/linkgo1.26.11、go1.27.4
GO-2026-6850CVE-2026-97041Host linker flag injection via //go:cgo_* directives in cmd/compile and cmd/linkgo1.26.11、go1.27.4
GO-2026-6849CVE-2026-97042Linker flag injection via cgo_import_dynamic and PE DLL names in cmd/cgo, cmd/compile, and cmd/linkgo1.26.11、go1.27.4
GO-2026-6848CVE-2026-97043Unexpected code execution via escaped quotes in //go:cgo_ldflag in cmd/go and cmd/compilego1.26.11、go1.27.4
GO-2026-6809CVE-2026-111943Distrust compromised intermediate certificates in crypto/x509go1.26.10、go1.27.3
GO-2026-6617CVE-2026-97032HTTP/2 server crash due to HPACK encoder race in net/httpgo1.26.9、go1.27.2
GO-2026-6617CVE-2026-97032HTTP/2 server crash due to HPACK encoder race in net/httpgo1.26.9、go1.27.2
GO-2026-6613CVE-2026-94439HTTP/1 server connection desynchronization after 2xx CONNECT response in net/httpgo1.26.9、go1.27.2
GO-2026-6612CVE-2026-78663Double flow control refund on HTTP/2 server streams in net/httpgo1.26.9、go1.27.2
GO-2026-6612CVE-2026-78663Double flow control refund on HTTP/2 server streams in net/httpgo1.26.9、go1.27.2
GO-2026-6611CVE-2026-78669Excessive CPU consumption from repeated initial window changes in net/httpgo1.26.9、go1.27.2
GO-2026-6611CVE-2026-78669Excessive CPU consumption from repeated initial window changes in net/httpgo1.26.9、go1.27.2
GO-2026-6610CVE-2026-78660HTTP/2 transport accepts malformed framing-related headers in net/httpgo1.26.9、go1.27.2
GO-2026-6610CVE-2026-78660HTTP/2 transport accepts malformed framing-related headers in net/httpgo1.26.9、go1.27.2
GO-2026-6609CVE-2026-78667Lack of limit on size of parsed Range headers in net/httpgo1.26.9、go1.27.2
GO-2026-6608CVE-2026-94440Memory limit bypass when parsing MIME headers in net/textproto, mime/multipartgo1.26.9、go1.27.2
GO-2026-6607CVE-2026-97031Reject malformed ECH outer extension references in crypto/tlsgo1.26.9、go1.27.2
GO-2026-6605CVE-2026-56866HTTP/1 client connection desynchronization after CONNECT rejection in net/httpgo1.26.9、go1.27.2
GO-2026-6604CVE-2026-56857Root.Mkdir(All) can follow junctions out of the root on Windows in osgo1.26.9、go1.27.2
GO-2026-6603CVE-2026-78659HTTP/2 server memory exhaustion due to Trailer headers in net/httpgo1.26.9、go1.27.2
GO-2026-6603CVE-2026-78659HTTP/2 server memory exhaustion due to Trailer headers in net/httpgo1.26.9、go1.27.2
GO-2026-6602CVE-2026-94447Checksum database bypass for golang.org/toolchain in cmd/gogo1.26.9、go1.27.2
GO-2026-6601CVE-2026-94444Checksum bypass for golang.org/fips140 in cmd/gogo1.26.9、go1.27.2
GO-2026-6600CVE-2026-97030Recognize yield as regexp preceder keyword in html/templatego1.26.9、go1.27.2
GO-2026-6599CVE-2026-94448Reset context tracking on consecutive template expressions in html/templatego1.26.9、go1.27.2
GO-2026-6218CVE-2026-56860Avoid quadratic complexity in resolvePath in net/urlgo1.25.13、go1.26.6、go1.27.0-rc.3
GO-2026-6180CVE-2026-56864Ignore unrelated, unauthenticated hashes in Lookup in golang.org/x/mod/sumdbgo1.25.13、go1.26.6、go1.27.0-rc.3
GO-2026-6179CVE-2026-56865Fix transparency log tile verification bypass in golang.org/x/mod/sumdb/tloggo1.25.13、go1.26.6、go1.27.0-rc.3
GO-2026-6091CVE-2026-56858Fix Javascript regexp context tracking in html/templatego1.25.13、go1.26.6、go1.27.0-rc.3
GO-2026-6090CVE-2026-56862Limit handshake messages we are willing to accept post-handshake in crypto/tlsgo1.25.13、go1.26.6、go1.27.0-rc.3
GO-2026-6089CVE-2026-56853Apply ReadHeaderTimeout when doing unencrypted HTTP/2 check in net/httpgo1.25.13、go1.26.6、go1.27.0-rc.3
GO-2026-6088CVE-2026-56859Add recursion depth guard during decode in encoding/xmlgo1.25.13、go1.26.6、go1.27.0-rc.3
GO-2026-5972CVE-2026-33818Enforce maximum recursion depth in encoding/asn1go1.25.13、go1.26.6、go1.27.0-rc.3
GO-2026-5942CVE-2026-46600Parsing an invalid SVCB or HTTPS RR can panic in golang.org/x/net/dns/dnsmessagego1.26.6、go1.27.0-rc.3
GO-2026-5856CVE-2026-42505Invoking Encrypted Client Hello privacy leak in crypto/tlsgo1.25.12、go1.26.5、go1.27.0-rc.2
GO-2026-5026CVE-2026-39821Invoking failure to reject ASCII-only Punycode-encoded labels in golang.org/x/net/idnago1.25.13、go1.26.6、go1.27.0-rc.3
GO-2026-4970CVE-2026-39822Root escape via symlink plus trailing slash in osgo1.25.12、go1.26.5、go1.27.0-rc.2

資料來源