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關閉。asynctimerchanGODEBUG 永久移除,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/1Response.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。範例:
- package main
- import (
- "fmt"
- "strconv"
- )
- type List[T any] struct {
- items []T
- }
- func (l List[T]) Map[U any](f func(T) U) List[U] {
- out := List[U]{}
- for _, v := range l.items {
- out.items = append(out.items, f(v))
- }
- return out
- }
- type Bag struct {
- values []int
- }
- func (b Bag) Format[S ~string](prefix S) []S {
- var out []S
- for _, v := range b.values {
- out = append(out, prefix+S(strconv.Itoa(v)))
- }
- return out
- }
- func main() {
- nums := List[int]{items: []int{1, 2, 3}}
- strs := nums.Map(func(n int) string { return fmt.Sprintf("<%d>", n) })
- fmt.Println(strs.items)
- type Label string
- fmt.Println(Bag{values: []int{7, 8}}.Format(Label("id-")))
- }
輸出:
- [<1> <2> <3>]
- [id-7 id-8]
注意:泛型方法不能拿來滿足介面;介面裡的方法也不能宣告型別參數。
結構字面值使用提升欄位
嵌入(embedding)的結構,其欄位會被「提升」到外層,可以直接用
u.ID 存取,但以前建立時必須寫成 User{Base: Base{ID: 1}}。現在字面值的鍵可以直接寫提升欄位 ID、Kind,讀寫寫法一致。詳見 嵌入。範例:
- package main
- import "fmt"
- type Base struct {
- ID int
- Kind string
- }
- type User struct {
- Base
- Name string
- }
- func main() {
- u := User{ID: 1, Kind: "admin", Name: "gopher"}
- fmt.Printf("%+v\n", u)
- }
輸出:
- {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。範例:
- package main
- import (
- "encoding/json/v2"
- "fmt"
- )
- type Config struct {
- Host string `json:"host"`
- Port int `json:"port"`
- }
- func main() {
- var c Config
- err := json.Unmarshal([]byte(`{"host":"localhost","port":8080}`), &c)
- fmt.Println(c, err)
- err = json.Unmarshal([]byte(`{"host":"a","host":"b"}`), &c)
- fmt.Println(err)
- err = json.Unmarshal([]byte(`{"host":"a","debug":true}`), &c, json.RejectUnknownMembers(true))
- fmt.Println(err)
- out, _ := json.Marshal(map[string]int{"b": 2, "a": 1}, json.Deterministic(true))
- fmt.Println(string(out))
- }
輸出:
- {localhost 8080} <nil>
- jsontext: duplicate object member name "host"
- json: cannot unmarshal JSON string into Go main.Config: unknown object member name "debug"
- {"a":1,"b":2}
uuid
UUID 是 128 位元的唯一識別碼,以前需要第三方套件。
uuid.Parse 解析字串(不分大小寫),失敗時回傳錯誤;uuid.New 產生隨機的第 4 版;uuid.NewV7 產生含時間戳記、依建立順序遞增的第 7 版,適合當資料庫主鍵。UUID 是 16 位元組陣列,可以直接用 == 比較。範例中隨機產生的值每次不同,所以只印長度與比較結果。範例:
- package main
- import (
- "fmt"
- "uuid"
- )
- func main() {
- id, err := uuid.Parse("f47ac10b-58cc-4372-a567-0e02b2c3d479")
- if err != nil {
- fmt.Println("error:", err)
- return
- }
- fmt.Println(id)
- fmt.Println(id == uuid.MustParse("F47AC10B-58CC-4372-A567-0E02B2C3D479"))
- a := uuid.NewV7()
- b := uuid.NewV7()
- fmt.Println(len(a.String()), a.Compare(b) < 0, a != uuid.Nil())
- _, err = uuid.Parse("not-a-uuid")
- fmt.Println(err)
- }
輸出:
- f47ac10b-58cc-4372-a567-0e02b2c3d479
- true
- 36 true true
- invalid uuid
strings.CutLast 與 Rand.N 方法
strings.CutLast 在最後一個分隔符號處切開,適合取出副檔名或檔名,取代 LastIndex 再自己切片的寫法。math/rand/v2 的 Rand 現在也有泛型方法 N,和頂層的 rand.N 一樣能產生 time.Duration 等任何整數型別的亂數。範例:
- package main
- import (
- "fmt"
- "math/rand/v2"
- "strings"
- "time"
- )
- func main() {
- dir, file, found := strings.CutLast("/var/log/app/server.log", "/")
- fmt.Println(dir, file, found)
- name, ext, _ := strings.CutLast("archive.tar.gz", ".")
- fmt.Println(name, ext)
- r := rand.New(rand.NewPCG(1, 2))
- d := r.N(10 * time.Second)
- fmt.Println(d >= 0 && d < 10*time.Second)
- }
輸出:
- /var/log/app server.log true
- archive.tar gz
- true
本版新增的棄用 API
以下 API 從 Go 1.27 起標記為棄用(Deprecated),新程式不要再使用;說明欄為官方原文。
| 套件 | 符號 | 官方說明 |
|---|---|---|
crypto/tls | Config.Rand | this 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.1 | 2026-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.2 | 2026-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.3 | 2026-10-19 | 是 | includes security fixes to the crypto/x509 package. |
go1.27.4 | 2026-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-6859 | CVE-2026-97054 | HTTP/1 server crash due to MaxBytesReader header race in net/http | go1.26.11、go1.27.4 |
| GO-2026-6858 | CVE-2026-97033 | Unexpected code execution via --sysroot, -target, -isysroot, -Wl,-syslibroot, and -x cgo flags in cmd/go | go1.26.11、go1.27.4 |
| GO-2026-6857 | CVE-2026-97034 | Arbitrary command execution via GCC spec files in cgo linker search directories in cmd/go | go1.26.11、go1.27.4 |
| GO-2026-6856 | CVE-2026-97035 | Unexpected code execution and arbitrary file write via Clang -gen-* and GCC -gnat* flags in cgo in cmd/go | go1.26.11、go1.27.4 |
| GO-2026-6855 | CVE-2026-97036 | Arbitrary code execution during build on darwin via "-l to_library" in cgo in cmd/go | go1.26.11、go1.27.4 |
| GO-2026-6854 | CVE-2026-97037 | Linker script injection via split -Wl, flags and Darwin or symbol linker flags in cgo in cmd/go | go1.26.11、go1.27.4 |
| GO-2026-6853 | CVE-2026-97038 | Arbitrary code execution via crafted .syso files and cgo linker input files in cmd/go | go1.26.11、go1.27.4 |
| GO-2026-6852 | CVE-2026-97039 | Flag sanitization bypass via "#cgo pkg-config:" directives in cmd/go | go1.26.11、go1.27.4 |
| GO-2026-6851 | CVE-2026-97040 | Cgo directive injection via .syso files disguised as Go object files in cmd/go and cmd/link | go1.26.11、go1.27.4 |
| GO-2026-6850 | CVE-2026-97041 | Host linker flag injection via //go:cgo_* directives in cmd/compile and cmd/link | go1.26.11、go1.27.4 |
| GO-2026-6849 | CVE-2026-97042 | Linker flag injection via cgo_import_dynamic and PE DLL names in cmd/cgo, cmd/compile, and cmd/link | go1.26.11、go1.27.4 |
| GO-2026-6848 | CVE-2026-97043 | Unexpected code execution via escaped quotes in //go:cgo_ldflag in cmd/go and cmd/compile | go1.26.11、go1.27.4 |
| GO-2026-6809 | CVE-2026-111943 | Distrust compromised intermediate certificates in crypto/x509 | go1.26.10、go1.27.3 |
| GO-2026-6617 | CVE-2026-97032 | HTTP/2 server crash due to HPACK encoder race in net/http | go1.26.9、go1.27.2 |
| GO-2026-6617 | CVE-2026-97032 | HTTP/2 server crash due to HPACK encoder race in net/http | go1.26.9、go1.27.2 |
| GO-2026-6613 | CVE-2026-94439 | HTTP/1 server connection desynchronization after 2xx CONNECT response in net/http | go1.26.9、go1.27.2 |
| GO-2026-6612 | CVE-2026-78663 | Double flow control refund on HTTP/2 server streams in net/http | go1.26.9、go1.27.2 |
| GO-2026-6612 | CVE-2026-78663 | Double flow control refund on HTTP/2 server streams in net/http | go1.26.9、go1.27.2 |
| GO-2026-6611 | CVE-2026-78669 | Excessive CPU consumption from repeated initial window changes in net/http | go1.26.9、go1.27.2 |
| GO-2026-6611 | CVE-2026-78669 | Excessive CPU consumption from repeated initial window changes in net/http | go1.26.9、go1.27.2 |
| GO-2026-6610 | CVE-2026-78660 | HTTP/2 transport accepts malformed framing-related headers in net/http | go1.26.9、go1.27.2 |
| GO-2026-6610 | CVE-2026-78660 | HTTP/2 transport accepts malformed framing-related headers in net/http | go1.26.9、go1.27.2 |
| GO-2026-6609 | CVE-2026-78667 | Lack of limit on size of parsed Range headers in net/http | go1.26.9、go1.27.2 |
| GO-2026-6608 | CVE-2026-94440 | Memory limit bypass when parsing MIME headers in net/textproto, mime/multipart | go1.26.9、go1.27.2 |
| GO-2026-6607 | CVE-2026-97031 | Reject malformed ECH outer extension references in crypto/tls | go1.26.9、go1.27.2 |
| GO-2026-6605 | CVE-2026-56866 | HTTP/1 client connection desynchronization after CONNECT rejection in net/http | go1.26.9、go1.27.2 |
| GO-2026-6604 | CVE-2026-56857 | Root.Mkdir(All) can follow junctions out of the root on Windows in os | go1.26.9、go1.27.2 |
| GO-2026-6603 | CVE-2026-78659 | HTTP/2 server memory exhaustion due to Trailer headers in net/http | go1.26.9、go1.27.2 |
| GO-2026-6603 | CVE-2026-78659 | HTTP/2 server memory exhaustion due to Trailer headers in net/http | go1.26.9、go1.27.2 |
| GO-2026-6602 | CVE-2026-94447 | Checksum database bypass for golang.org/toolchain in cmd/go | go1.26.9、go1.27.2 |
| GO-2026-6601 | CVE-2026-94444 | Checksum bypass for golang.org/fips140 in cmd/go | go1.26.9、go1.27.2 |
| GO-2026-6600 | CVE-2026-97030 | Recognize yield as regexp preceder keyword in html/template | go1.26.9、go1.27.2 |
| GO-2026-6599 | CVE-2026-94448 | Reset context tracking on consecutive template expressions in html/template | go1.26.9、go1.27.2 |
| GO-2026-6218 | CVE-2026-56860 | Avoid quadratic complexity in resolvePath in net/url | go1.25.13、go1.26.6、go1.27.0-rc.3 |
| GO-2026-6180 | CVE-2026-56864 | Ignore unrelated, unauthenticated hashes in Lookup in golang.org/x/mod/sumdb | go1.25.13、go1.26.6、go1.27.0-rc.3 |
| GO-2026-6179 | CVE-2026-56865 | Fix transparency log tile verification bypass in golang.org/x/mod/sumdb/tlog | go1.25.13、go1.26.6、go1.27.0-rc.3 |
| GO-2026-6091 | CVE-2026-56858 | Fix Javascript regexp context tracking in html/template | go1.25.13、go1.26.6、go1.27.0-rc.3 |
| GO-2026-6090 | CVE-2026-56862 | Limit handshake messages we are willing to accept post-handshake in crypto/tls | go1.25.13、go1.26.6、go1.27.0-rc.3 |
| GO-2026-6089 | CVE-2026-56853 | Apply ReadHeaderTimeout when doing unencrypted HTTP/2 check in net/http | go1.25.13、go1.26.6、go1.27.0-rc.3 |
| GO-2026-6088 | CVE-2026-56859 | Add recursion depth guard during decode in encoding/xml | go1.25.13、go1.26.6、go1.27.0-rc.3 |
| GO-2026-5972 | CVE-2026-33818 | Enforce maximum recursion depth in encoding/asn1 | go1.25.13、go1.26.6、go1.27.0-rc.3 |
| GO-2026-5942 | CVE-2026-46600 | Parsing an invalid SVCB or HTTPS RR can panic in golang.org/x/net/dns/dnsmessage | go1.26.6、go1.27.0-rc.3 |
| GO-2026-5856 | CVE-2026-42505 | Invoking Encrypted Client Hello privacy leak in crypto/tls | go1.25.12、go1.26.5、go1.27.0-rc.2 |
| GO-2026-5026 | CVE-2026-39821 | Invoking failure to reject ASCII-only Punycode-encoded labels in golang.org/x/net/idna | go1.25.13、go1.26.6、go1.27.0-rc.3 |
| GO-2026-4970 | CVE-2026-39822 | Root escape via symlink plus trailing slash in os | go1.25.12、go1.26.5、go1.27.0-rc.2 |