# Go 1.21

Go 1.21 發布於 2023-08-08，目前最新修補版為 `go1.21.13`，**已停止支援**，請升級到 `go1.27.4`。

## 版本介紹

Go 1.21 讓日常程式碼一口氣變簡潔：新增內建函式 `min`、`max`、`clear`，標準庫加入泛型的 `slices`、`maps`、`cmp` 套件，以及官方結構化日誌套件 `log/slog`。工具鏈也開始「自動管理 Go 版本」：`go.mod` 的 `go` 行變成嚴格的最低需求，本機版本太舊時可自動下載對應工具鏈。升級時要注意：`panic(nil)` 現在會變成 `*runtime.PanicNilError`；套件初始化順序有了明確定義，依賴隱含順序的程式可能改變行為；PGO 正式可用並在 main 套件有 `default.pgo` 時自動啟用。

### 語言變更

- 新增內建函式 `min`、`max`，可傳入任意多個同型別的可排序值；`clear` 清空映射或把切片元素歸零。
- 型別推斷更強：把泛型函式當引數傳入、指派給變數時，多數情況可以省略型別參數。
- `panic(nil)` 改為觸發 `*runtime.PanicNilError`，保證 `recover()` 在 panic 中不會回傳 `nil`。
- 套件初始化順序改為「依匯入路徑排序，逐一初始化相依已完成的套件」，規則明確。
- 以預覽方式提供「每次迭代一個新迴圈變數」的實驗（`GOEXPERIMENT=loopvar`），於 Go 1.22 正式生效。

### 工具

- `go.mod` 的 `go 1.21.0` 代表最低需求，舊版工具鏈會明確拒絕；新增 `toolchain` 行指定建議的工具鏈。
- 本機 Go 版本不足時，`go` 指令可依 `GOTOOLCHAIN` 設定自動下載並切換到需要的版本。
- 版本號改為 `1.21.0` 這種三段式；第一個正式版不再是 `1.21`。
- `-pgo` 預設為 `auto`，main 套件目錄有 `default.pgo` 就會自動使用，詳見 [PGO](/perf-pgo)。
- 新增實驗性的 WASI 移植（`GOOS=wasip1`），可編譯成在 WebAssembly 執行環境執行的程式。

### 執行時與效能

- PGO 正式可用，多數程式啟用後提升 2–7%，還能把常見的介面方法呼叫去虛擬化（devirtualize）。
- GC 內部調校後，部分應用的尾端延遲（tail latency）最多降低 40%。
- 在 C 建立的執行緒上反覆從 C 呼叫 Go，每次的額外開銷從約 1–3 微秒降到 100–200 奈秒。
- 堆疊很深時，panic 訊息改為印出最內層 50 層與最外層 50 層，方便追查遞迴的起點。

### 標準庫重點

- 新增 `log/slog`：結構化日誌，輸出 `key=value` 或 JSON，詳見 [slog](/logging-slog)。
- 新增 `slices`、`maps`：排序、搜尋、比較、複製等泛型工具函式，詳見 [slices](/pkg-slices)、[maps](/pkg-maps)。
- 新增 `cmp`：提供 `Ordered` 約束與 `Compare`、`Less` 函式，詳見 [cmp](/pkg-cmp)。
- `sync` 新增 `OnceFunc`、`OnceValue`、`OnceValues`，把「只執行一次」包成函式。
- `context` 新增 `WithoutCancel`、`WithDeadlineCause`、`WithTimeoutCause`、`AfterFunc`。
- 新增 `testing/slogtest`，用來驗證自訂的 `slog.Handler`。

### min、max 與 clear

`min`、`max` 不必再自己寫比較函式，也能比較字串（依字典順序）。`clear` 作用在映射時刪除所有鍵；作用在切片時把每個元素設為零值，長度不變。

範例：

```go
package main

import "fmt"

func main() {
	fmt.Println(min(3, 1, 2), max(2.5, 1.0))
	fmt.Println(min("banana", "apple"))

	m := map[string]int{"a": 1, "b": 2}
	clear(m)
	fmt.Println(len(m))

	s := []int{1, 2, 3}
	clear(s)
	fmt.Println(s, len(s))
}
```

輸出：

```text
1 2.5
apple
0
[0 0 0] 3
```

### slices、maps 與 cmp

`slices.Sort` 排序、`slices.Contains` 檢查是否包含、`slices.Compact` 去掉相鄰重複值。`slices.SortFunc` 搭配 `cmp.Compare` 可自訂排序規則：回傳負數代表 a 排前面。`maps.Clone` 複製映射，修改複本不影響原本的映射。

範例：

```go
package main

import (
	"cmp"
	"fmt"
	"maps"
	"slices"
)

type User struct {
	Name string
	Age  int
}

func main() {
	nums := []int{5, 2, 8, 2}
	slices.Sort(nums)
	fmt.Println(nums, slices.Contains(nums, 8), slices.Index(nums, 5))
	fmt.Println(slices.Compact(nums))

	users := []User{{"Bob", 30}, {"Amy", 25}, {"Cid", 30}}
	slices.SortFunc(users, func(a, b User) int {
		if c := cmp.Compare(a.Age, b.Age); c != 0 {
			return c
		}
		return cmp.Compare(a.Name, b.Name)
	})
	fmt.Println(users)

	src := map[string]int{"x": 1}
	dst := maps.Clone(src)
	dst["y"] = 2
	fmt.Println(len(src), len(dst), maps.Equal(src, dst))
}
```

輸出：

```text
[2 2 5 8] true 2
[2 5 8]
[{Amy 25} {Bob 30} {Cid 30}]
1 2 false
```

### log/slog

`slog` 的每筆日誌都有等級、訊息與一組鍵值屬性，方便日後用程式搜尋與統計。`NewTextHandler` 輸出 `key=value` 格式，`NewJSONHandler` 輸出 JSON。範例用 `ReplaceAttr` 拿掉時間欄位，讓輸出固定；預設等級是 `INFO`，所以 `Debug` 那筆不會印出。

範例：

```go
package main

import (
	"log/slog"
	"os"
)

func main() {
	handler := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
		ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
			if a.Key == slog.TimeKey && len(groups) == 0 {
				return slog.Attr{}
			}
			return a
		},
	})
	logger := slog.New(handler)
	logger.Info("user login", "user", "gopher", "id", 42)
	logger.With("service", "api").Warn("slow request", slog.Int("ms", 1200))
	logger.Debug("not shown")
}
```

輸出：

```text
level=INFO msg="user login" user=gopher id=42
level=WARN msg="slow request" service=api ms=1200
```

### sync.OnceValue

讀設定、建立連線這類「第一次用到才做、之後重複使用結果」的工作，以前要宣告 `sync.Once` 再搭配一個變數。`OnceValue` 回傳一個函式，第一次呼叫時執行並記住結果，之後直接回傳，即使多個 goroutine 同時呼叫也只會執行一次。

範例：

```go
package main

import (
	"fmt"
	"sync"
)

func main() {
	calls := 0
	loadConfig := sync.OnceValue(func() string {
		calls++
		return "config-v1"
	})
	fmt.Println(loadConfig(), loadConfig(), calls)
}
```

輸出：

```text
config-v1 config-v1 1
```

## 本版新增的棄用 API

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

| 套件 | 符號 | 官方說明 |
| --- | --- | --- |
| `crypto/elliptic` | `Curve.Add` | this is a low-level unsafe API. |
| `crypto/elliptic` | `Curve.Double` | this is a low-level unsafe API. |
| `crypto/elliptic` | `Curve.IsOnCurve` | this is a low-level unsafe API. For ECDH, use the crypto/ecdh package. The NewPublicKey methods of NIST curves in crypto/ecdh accept the same encoding as the Unmarshal function, and perform on-curve checks. |
| `crypto/elliptic` | `Curve.ScalarBaseMult` | this is a low-level unsafe API. For ECDH, use the crypto/ecdh package. Most uses of ScalarBaseMult can be replaced by a call to the PrivateKey.PublicKey method in crypto/ecdh. |
| `crypto/elliptic` | `Curve.ScalarMult` | this is a low-level unsafe API. For ECDH, use the crypto/ecdh package. Most uses of ScalarMult can be replaced by a call to the ECDH methods of NIST curves in crypto/ecdh. |
| `crypto/elliptic` | `CurveParams.Add` | the [CurveParams] methods are deprecated and are not guaranteed to provide any security property. For ECDH, use the [crypto/ecdh] package. For ECDSA, use the [crypto/ecdsa] package with a [Curve] value returned directly from [P224], [P256], [P384], or [P521]. |
| `crypto/elliptic` | `CurveParams.Double` | the [CurveParams] methods are deprecated and are not guaranteed to provide any security property. For ECDH, use the [crypto/ecdh] package. For ECDSA, use the [crypto/ecdsa] package with a [Curve] value returned directly from [P224], [P256], [P384], or [P521]. |
| `crypto/elliptic` | `CurveParams.IsOnCurve` | the [CurveParams] methods are deprecated and are not guaranteed to provide any security property. For ECDH, use the [crypto/ecdh] package. For ECDSA, use the [crypto/ecdsa] package with a [Curve] value returned directly from [P224], [P256], [P384], or [P521]. |
| `crypto/elliptic` | `CurveParams.ScalarBaseMult` | the [CurveParams] methods are deprecated and are not guaranteed to provide any security property. For ECDH, use the [crypto/ecdh] package. For ECDSA, use the [crypto/ecdsa] package with a [Curve] value returned directly from [P224], [P256], [P384], or [P521]. |
| `crypto/elliptic` | `CurveParams.ScalarMult` | the [CurveParams] methods are deprecated and are not guaranteed to provide any security property. For ECDH, use the [crypto/ecdh] package. For ECDSA, use the [crypto/ecdsa] package with a [Curve] value returned directly from [P224], [P256], [P384], or [P521]. |
| `crypto/elliptic` | `GenerateKey` | for ECDH, use the GenerateKey methods of the [crypto/ecdh] package; for ECDSA, use the GenerateKey function of the crypto/ecdsa package. |
| `crypto/elliptic` | `Marshal` | for ECDH, use the crypto/ecdh package. This function returns an encoding equivalent to that of PublicKey.Bytes in crypto/ecdh. |
| `crypto/elliptic` | `Unmarshal` | for ECDH, use the crypto/ecdh package. This function accepts an encoding equivalent to that of the NewPublicKey methods in crypto/ecdh. |
| `crypto/rsa` | `GenerateMultiPrimeKey` | The use of this function with a number of primes different from two is not recommended for the above security, compatibility, and performance reasons. Use [GenerateKey] instead. |
| `crypto/rsa` | `PrecomputedValues.CRTValues` | These values are still filled in by Precompute for backwards compatibility but are not used. Multi-prime RSA is very rare, and is implemented by this package without CRT optimizations to limit complexity. |
| `crypto/x509` | `RevocationList.RevokedCertificates` | Use RevokedCertificateEntries instead. |
| `reflect` | `SliceHeader` | Use unsafe.Slice or unsafe.SliceData instead. |
| `reflect` | `StringHeader` | Use unsafe.String or unsafe.StringData instead. |

## 修補版本

| 版本 | 發布日期 | 含安全修補 | 內容（官方原文） |
| --- | --- | --- | --- |
| `go1.21.1` | 2023-09-06 | 是 | includes four security fixes to the cmd/go, crypto/tls, and html/template packages, as well as bug fixes to the compiler, the go command, the linker, the runtime, and the context, crypto/tls, encoding/gob, encoding/xml, go/types, net/http, os, and path/filepath packages. |
| `go1.21.2` | 2023-10-05 | 是 | includes one security fix to the cmd/go package, as well as bug fixes to the compiler, the go command, the linker, the runtime, and the runtime/metrics package. |
| `go1.21.3` | 2023-10-10 | 是 | includes a security fix to the net/http package. |
| `go1.21.4` | 2023-11-07 | 是 | includes security fixes to the path/filepath package, as well as bug fixes to the linker, the runtime, the compiler, and the go/types, net/http, and runtime/cgo packages. |
| `go1.21.5` | 2023-12-05 | 是 | includes security fixes to the go command, and the net/http and path/filepath packages, as well as bug fixes to the compiler, the go command, the runtime, and the crypto/rand, net, os, and syscall packages. |
| `go1.21.6` | 2024-01-09 | 否 | includes fixes to the compiler, the runtime, and the crypto/tls, maps, and runtime/pprof packages. |
| `go1.21.7` | 2024-02-06 | 否 | includes fixes to the compiler, the go command, the runtime, and the crypto/x509 package. |
| `go1.21.8` | 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 go command and the runtime. |
| `go1.21.9` | 2024-04-03 | 是 | includes a security fix to the net/http package, as well as bug fixes to the linker, and the go/types and net/http packages. |
| `go1.21.10` | 2024-05-07 | 是 | includes security fixes to the go command, as well as bug fixes to the net/http package. |
| `go1.21.11` | 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 runtime, and the os package. |
| `go1.21.12` | 2024-07-02 | 是 | includes security fixes to the net/http package, as well as bug fixes to the compiler, the go command, the runtime, and the crypto/x509, net/http, net/netip, and os packages. |
| `go1.21.13` | 2024-08-06 | 否 | includes fixes to the go command, the covdata command, and the bytes package. |

## 已知漏洞

在 Go 1.21 系列修補版中修正的漏洞共 24 個；仍影響最新修補版 `go1.21.13` 的漏洞共 103 個。

### 本系列已修正

| 編號 | CVE | 摘要（官方原文） | 修正於 |
| --- | --- | --- | --- |
| [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-2962](https://pkg.go.dev/vuln/GO-2024-2962) | CVE-2023-24531 | Output of "go env" does not sanitize values in cmd/go | go1.21.0-0 |
| [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-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 |
| [GO-2023-2383](https://pkg.go.dev/vuln/GO-2023-2383) | CVE-2023-45285 | Command 'go get' may unexpectedly fallback to insecure git in cmd/go | go1.20.12、go1.21.5 |
| [GO-2023-2382](https://pkg.go.dev/vuln/GO-2023-2382) | CVE-2023-39326 | Denial of service via chunk extensions in net/http | go1.20.12、go1.21.5 |
| [GO-2023-2186](https://pkg.go.dev/vuln/GO-2023-2186) | CVE-2023-45284 | Incorrect detection of reserved device names on Windows in path/filepath | go1.20.11、go1.21.4 |
| [GO-2023-2185](https://pkg.go.dev/vuln/GO-2023-2185) | CVE-2023-45283 | Insecure parsing of Windows paths with a \??\ prefix in path/filepath | go1.20.11、go1.21.4、go1.20.12、go1.21.5 |
| [GO-2023-2185](https://pkg.go.dev/vuln/GO-2023-2185) | CVE-2023-45283 | Insecure parsing of Windows paths with a \??\ prefix in path/filepath | go1.20.11、go1.21.4、go1.20.12、go1.21.5 |
| [GO-2023-2102](https://pkg.go.dev/vuln/GO-2023-2102) | CVE-2023-39325 | HTTP/2 rapid reset can cause excessive work in net/http | go1.20.10、go1.21.3 |
| [GO-2023-2095](https://pkg.go.dev/vuln/GO-2023-2095) | CVE-2023-39323 | Arbitrary code execution during build via line directives in cmd/go | go1.20.9、go1.21.2 |
| [GO-2023-2045](https://pkg.go.dev/vuln/GO-2023-2045) | CVE-2023-39322 | Memory exhaustion in QUIC connection handling in crypto/tls | go1.21.1 |
| [GO-2023-2044](https://pkg.go.dev/vuln/GO-2023-2044) | CVE-2023-39321 | Panic when processing post-handshake message on QUIC connections in crypto/tls | go1.21.1 |
| [GO-2023-2043](https://pkg.go.dev/vuln/GO-2023-2043) | CVE-2023-39319 | Improper handling of special tags within script contexts in html/template | go1.20.8、go1.21.1 |
| [GO-2023-2042](https://pkg.go.dev/vuln/GO-2023-2042) | CVE-2023-39320 | Arbitrary code execution via go.mod toolchain directive in cmd/go | go1.21.1 |
| [GO-2023-2041](https://pkg.go.dev/vuln/GO-2023-2041) | CVE-2023-39318 | Improper handling of HTML-like comments in script contexts in html/template | go1.20.8、go1.21.1 |
| [GO-2023-1987](https://pkg.go.dev/vuln/GO-2023-1987) | CVE-2023-29409 | Large RSA keys can cause high CPU usage in crypto/tls | go1.19.12、go1.20.7、go1.21.0-rc.4 |

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


## 資料來源

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