# 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](/control-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](/pkg-math-rand-v2)。
- `net/http.ServeMux` 樣式可以寫 HTTP 方法與 `{name}` 路徑參數，用 `Request.PathValue` 取值，詳見 [net/http](/pkg-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`，結果符合直覺。

範例：

```go
package main

import (
	"fmt"
	"sync"
)

func main() {
	var wg sync.WaitGroup
	results := make([]string, 3)
	for i, name := range []string{"a", "b", "c"} {
		wg.Add(1)
		go func() {
			defer wg.Done()
			results[i] = fmt.Sprintf("%d:%s", i, name)
		}()
	}
	wg.Wait()
	fmt.Println(results)

	var funcs []func() int
	for i := 0; i < 3; i++ {
		funcs = append(funcs, func() int { return i })
	}
	for _, f := range funcs {
		fmt.Print(f(), " ")
	}
	fmt.Println()
}
```

輸出：

```text
[0:a 1:b 2:c]
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 時迴圈一次都不執行。

範例：

```go
package main

import "fmt"

func main() {
	for i := range 3 {
		fmt.Println("round", i)
	}
	total := 0
	for range 5 {
		total++
	}
	fmt.Println(total)
}
```

輸出：

```text
round 0
round 1
round 2
5
```

### 增強的 ServeMux 路由

以前標準庫的路由只能比對路徑前綴，要分辨 GET／POST 或取出路徑中的 ID，多半得用第三方路由器。現在樣式可以寫成 `"GET /users/{id}"`：方法不符時自動回 `405 Method Not Allowed`，`{id}` 用 `r.PathValue("id")` 取得。範例用 `httptest` 起一個本機伺服器。

範例：

```go
package main

import (
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"
	"strings"
)

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("GET /users/{id}", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "get user %s", r.PathValue("id"))
	})
	mux.HandleFunc("POST /users", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprint(w, "created")
	})
	srv := httptest.NewServer(mux)
	defer srv.Close()

	show := func(resp *http.Response, err error) {
		if err != nil {
			fmt.Println("error:", err)
			return
		}
		defer resp.Body.Close()
		body, _ := io.ReadAll(resp.Body)
		fmt.Println(resp.StatusCode, strings.TrimSpace(string(body)))
	}
	show(http.Get(srv.URL + "/users/42"))
	show(http.Post(srv.URL+"/users", "text/plain", nil))
	show(http.Post(srv.URL+"/users/42", "text/plain", nil))
}
```

輸出：

```text
200 get user 42
200 created
405 Method Not Allowed
```

### math/rand/v2

`rand.New(rand.NewPCG(1, 2))` 用固定種子建立產生器，每次執行結果相同，適合測試。方法名稱改得更一致，例如 `Intn` 改為 `IntN`；新的泛型函式 `rand.N` 可以產生任何整數型別（包含 `time.Duration`）的亂數。頂層函式使用自動隨機播種的全域產生器，不需要也不能手動設定種子。

範例：

```go
package main

import (
	"fmt"
	"math/rand/v2"
)

func main() {
	r := rand.New(rand.NewPCG(1, 2))
	fmt.Println(r.IntN(100), r.IntN(100), r.IntN(100))
	fmt.Println(r.Float64() < 1)

	n := rand.N(10)
	fmt.Println(n >= 0 && n < 10)
}
```

輸出：

```text
76 61 78
true
true
```

## 本版新增的棄用 API

以下 API 從 Go 1.22 起標記為棄用（Deprecated），新程式不要再使用；說明欄為官方原文。

| 套件 | 符號 | 官方說明 |
| --- | --- | --- |
| `go/ast` | `Importer` | use the type checker [go/types] instead; see [Object]. |
| `go/ast` | `NewPackage` | use the type checker [go/types] instead; see [Object]. |
| `go/ast` | `Object` | The 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/ast` | `Package` | use the type checker [go/types] instead; see [Object]. |
| `go/ast` | `Scope` | use the type checker [go/types] instead; see [Object]. |
| `html/template` | `ErrJSTemplate` | ErrJSTemplate 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. |
| `reflect` | `PtrTo` | Superseded by [PointerTo]. |

## 修補版本

| 版本 | 發布日期 | 含安全修補 | 內容（官方原文） |
| --- | --- | --- | --- |
| `go1.22.1` | 2024-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.2` | 2024-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.3` | 2024-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.4` | 2024-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.5` | 2024-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.6` | 2024-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.7` | 2024-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.8` | 2024-10-01 | 否 | includes fixes to cgo, and the maps and syscall packages. |
| `go1.22.9` | 2024-11-06 | 否 | includes fixes to the linker. |
| `go1.22.10` | 2024-12-03 | 否 | includes fixes to the runtime and the syscall package. |
| `go1.22.11` | 2025-01-16 | 是 | includes security fixes to the crypto/x509 and net/http packages, as well as bug fixes to the runtime. |
| `go1.22.12` | 2025-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-3447](https://pkg.go.dev/vuln/GO-2025-3447) | CVE-2025-22866 | Timing sidechannel for P-256 on ppc64le in crypto/internal/nistec | go1.22.12、go1.23.6、go1.24.0-rc.3 |
| [GO-2025-3420](https://pkg.go.dev/vuln/GO-2025-3420) | CVE-2024-45336 | Sensitive headers incorrectly sent after cross-domain redirect in net/http | go1.22.11、go1.23.5、go1.24.0-rc.2 |
| [GO-2025-3373](https://pkg.go.dev/vuln/GO-2025-3373) | CVE-2024-45341 | Usage of IPv6 zone IDs can bypass URI name constraints in crypto/x509 | go1.22.11、go1.23.5、go1.24.0-rc.2 |
| [GO-2024-3107](https://pkg.go.dev/vuln/GO-2024-3107) | CVE-2024-34158 | Stack exhaustion in Parse in go/build/constraint | go1.22.7、go1.23.1 |
| [GO-2024-3106](https://pkg.go.dev/vuln/GO-2024-3106) | CVE-2024-34156 | Stack exhaustion in Decoder.Decode in encoding/gob | go1.22.7、go1.23.1 |
| [GO-2024-3105](https://pkg.go.dev/vuln/GO-2024-3105) | CVE-2024-34155 | Stack exhaustion in all Parse functions in go/parser | go1.22.7、go1.23.1 |
| [GO-2024-2963](https://pkg.go.dev/vuln/GO-2024-2963) | CVE-2024-24791 | Denial of service due to improper 100-continue handling in net/http | go1.21.12、go1.22.5 |
| [GO-2024-2888](https://pkg.go.dev/vuln/GO-2024-2888) | CVE-2024-24789 | Mishandling of corrupt central directory record in archive/zip | go1.21.11、go1.22.4 |
| [GO-2024-2887](https://pkg.go.dev/vuln/GO-2024-2887) | CVE-2024-24790 | Unexpected behavior from Is methods for IPv4-mapped IPv6 addresses in net/netip | go1.21.11、go1.22.4 |
| [GO-2024-2825](https://pkg.go.dev/vuln/GO-2024-2825) | CVE-2024-24787 | Arbitrary code execution during build on Darwin in cmd/go | go1.21.10、go1.22.3 |
| [GO-2024-2824](https://pkg.go.dev/vuln/GO-2024-2824) | CVE-2024-24788 | Malformed DNS message can cause infinite loop in net | go1.22.3 |
| [GO-2024-2687](https://pkg.go.dev/vuln/GO-2024-2687) | CVE-2023-45288 | HTTP/2 CONTINUATION flood in net/http | go1.21.9、go1.22.2 |
| [GO-2024-2610](https://pkg.go.dev/vuln/GO-2024-2610) | CVE-2024-24785 | Errors returned from JSON marshaling may break template escaping in html/template | go1.21.8、go1.22.1 |
| [GO-2024-2609](https://pkg.go.dev/vuln/GO-2024-2609) | CVE-2024-24784 | Comments in display names are incorrectly handled in net/mail | go1.21.8、go1.22.1 |
| [GO-2024-2600](https://pkg.go.dev/vuln/GO-2024-2600) | CVE-2023-45289 | Incorrect forwarding of sensitive headers and cookies on HTTP redirect in net/http | go1.21.8、go1.22.1 |
| [GO-2024-2599](https://pkg.go.dev/vuln/GO-2024-2599) | CVE-2023-45290 | Memory exhaustion in multipart form parsing in net/textproto and net/http | go1.21.8、go1.22.1 |
| [GO-2024-2598](https://pkg.go.dev/vuln/GO-2024-2598) | CVE-2024-24783 | Verify panics on certificates with an unknown public key algorithm in crypto/x509 | go1.21.8、go1.22.1 |

本版已停止支援，不會再修正這些漏洞；完整清單見 [資安漏洞](/security)。


## 資料來源

- [Go 1.22 Release Notes](https://go.dev/doc/go1.22)
- [Go 發版歷史](https://go.dev/doc/devel/release#go1.22.0)
- [Go 漏洞資料庫](https://vuln.go.dev)
- [golang/go 原始碼 go1.22.0](https://github.com/golang/go/tree/go1.22.0)
