# Go 1.18

Go 1.18 發布於 2022-03-15，目前最新修補版為 `go1.18.10`，**已停止支援**，請升級到 `go1.27.4`。

## 版本介紹

Go 1.18 是 Go 1.0 以來語言變動最大的版本：正式加入泛型（generics），讓同一段程式碼能用在多種型別上，不必再為 `int`、`float64` 各寫一份，也不必退回 `interface{}` 加型別斷言。同一版還內建模糊測試（fuzzing）與工作區（workspace）模式。升級時要注意：為了支援泛型，編譯器的型別檢查器整個重寫，編譯速度約比 1.17 慢 15%，部分錯誤訊息的措辭也不同；用戶端 TLS 預設不再接受 TLS 1.0／1.1。

### 語言變更

- 函式與型別可以宣告型別參數（type parameter），用中括號寫在名稱後面，例如 `func Sum[T Number](v []T) T`，詳見 [泛型函式](/generics-functions)。
- 介面可以列出型別集合（type set），例如 `~int | ~float64`，當作型別參數的約束（constraint）；`~int` 表示「底層型別是 `int` 的所有型別」。
- 新增預先宣告的 `any`，它就是 `interface{}` 的別名，寫起來更短。
- 新增預先宣告的 `comparable` 約束，代表可以用 `==` 比較的型別，常用在映射的鍵。

### 工具

- `go test -fuzz` 內建模糊測試：自動產生大量隨機輸入找出會讓程式出錯的案例，詳見 [模糊測試](/testing-fuzzing)。
- 新增 `go work` 工作區模式，用 `go.work` 同時開發多個本機模組，不必改 `go.mod`，詳見 [工作區](/modules-workspace)。
- `go get` 不再編譯與安裝程式，只負責調整 `go.mod` 的相依；安裝執行檔改用 `go install pkg@version`。
- `go build` 會把版本控制資訊（commit、是否有未提交變更）寫進執行檔，可用 `-buildvcs=false` 關閉。
- `gofmt` 改為並行處理多個檔案，在多核心機器上明顯變快。

### 執行時與效能

- 以暫存器傳遞函式參數的呼叫慣例擴展到 64 位元 ARM（`arm64`）與 PowerPC，這些平台常見 10% 以上的效能提升。
- 垃圾回收（garbage collection，GC）決定何時執行時，會把堆疊掃描等非堆積的工作量一起算進去，GC 負擔更好預測。
- `append` 擴充切片容量的公式調整，配置行為更平滑。
- 編譯器現在能內聯（inline）含有 `range` 迴圈或帶標籤 `for` 迴圈的函式。

### 標準庫重點

- 新增 `net/netip` 套件，提供更省記憶體、可比較的 IP 位址型別。
- 新增 `debug/buildinfo` 套件，可讀取執行檔內嵌的模組與建置資訊。
- `strings.Cut` 與 `bytes.Cut` 一次把字串在分隔符號處切成前後兩段。
- `crypto/tls` 用戶端預設最低版本改為 TLS 1.2；`crypto/x509` 拒絕以 SHA-1 簽章的憑證。

### 泛型函式

泛型函式在名稱後面用 `[T 約束]` 宣告型別參數。呼叫時通常不必寫出型別，編譯器會從引數推斷（type inference）。下面的 `Number` 是只允許數字型別的約束，`Map` 則示範兩個型別參數。

範例：

```go
package main

import "fmt"

type Number interface {
	~int | ~int64 | ~float64
}

func Sum[T Number](values []T) T {
	var total T
	for _, v := range values {
		total += v
	}
	return total
}

func Map[T, U any](values []T, f func(T) U) []U {
	out := make([]U, 0, len(values))
	for _, v := range values {
		out = append(out, f(v))
	}
	return out
}

func main() {
	fmt.Println(Sum([]int{1, 2, 3}))
	fmt.Println(Sum([]float64{1.5, 2.25}))
	words := Map([]int{1, 2, 3}, func(n int) string {
		return fmt.Sprintf("#%d", n)
	})
	fmt.Println(words)
}
```

輸出：

```text
6
3.75
[#1 #2 #3]
```

### 泛型型別

型別也可以帶型別參數，寫一次 `Stack[T]` 就能裝任何型別。使用時要寫出具體型別，例如 `Stack[string]`；`var zero T` 取得該型別的零值，常用來在「沒有資料」時回傳。詳見 [泛型型別](/generics-types)。

範例：

```go
package main

import "fmt"

type Stack[T any] struct {
	items []T
}

func (s *Stack[T]) Push(v T) {
	s.items = append(s.items, v)
}

func (s *Stack[T]) Pop() (T, bool) {
	var zero T
	if len(s.items) == 0 {
		return zero, false
	}
	last := s.items[len(s.items)-1]
	s.items = s.items[:len(s.items)-1]
	return last, true
}

func main() {
	var s Stack[string]
	s.Push("a")
	s.Push("b")
	v, ok := s.Pop()
	fmt.Println(v, ok)
	v, ok = s.Pop()
	fmt.Println(v, ok)
	v, ok = s.Pop()
	fmt.Printf("%q %v\n", v, ok)
}
```

輸出：

```text
b true
a true
"" false
```

### net/netip

舊的 `net.IP` 是位元組切片，不能直接當映射的鍵，也不能用 `==` 比較。`netip.Addr` 是小巧的值型別，可以比較、可以當鍵，解析失敗時回傳錯誤。`Prefix` 表示網段，`Contains` 判斷位址是否在網段內。詳見 [net/netip](/pkg-net-netip)。

範例：

```go
package main

import (
	"fmt"
	"net/netip"
)

func main() {
	addr, err := netip.ParseAddr("192.168.1.10")
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	prefix := netip.MustParsePrefix("192.168.1.0/24")
	fmt.Println(addr, addr.Is4(), prefix.Contains(addr))

	seen := map[netip.Addr]bool{addr: true}
	other := netip.MustParseAddr("192.168.1.10")
	fmt.Println(seen[other])

	_, err = netip.ParseAddr("300.1.1.1")
	fmt.Println(err != nil)
}
```

輸出：

```text
192.168.1.10 true true
true
true
```

### strings.Cut

以前要切開 `key=value` 常寫 `strings.Index` 再自己算切片範圍，容易寫錯。`strings.Cut` 回傳分隔符號前、後兩段，以及是否找到；找不到時 `before` 是原字串、`after` 是空字串。

範例：

```go
package main

import (
	"fmt"
	"strings"
)

func main() {
	key, value, found := strings.Cut("name=gopher", "=")
	fmt.Println(key, value, found)

	key, value, found = strings.Cut("no-separator", "=")
	fmt.Printf("%q %q %v\n", key, value, found)
}
```

輸出：

```text
name gopher true
"no-separator" "" false
```

## 本版新增的棄用 API

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

| 套件 | 符號 | 官方說明 |
| --- | --- | --- |
| `bytes` | `Title` | The rule Title uses for word boundaries does not handle Unicode punctuation properly. Use golang.org/x/text/cases instead. |
| `crypto/tls` | `Config.PreferServerCipherSuites` | PreferServerCipherSuites is ignored. |
| `crypto/x509` | `CertPool.Subjects` | if s was returned by [SystemCertPool], Subjects will not include the system roots. |
| `go/types` | `Interface.Embedded` | Use [Interface.EmbeddedType] which is not restricted to defined (*[Named]) types. |
| `go/types` | `NewInterface` | Use NewInterfaceType instead which allows arbitrary embedded types. |
| `go/types` | `NewSignature` | Use [NewSignatureType] instead which allows for type parameters. |
| `net` | `Error.Temporary` | Temporary errors are not well-defined. Most "temporary" errors are timeouts, and the few exceptions are surprising. Do not use this method. |
| `strings` | `Title` | The rule Title uses for word boundaries does not handle Unicode punctuation properly. Use golang.org/x/text/cases instead. |
| `syscall` | `Syscall` | Use [SyscallN] instead. |
| `syscall` | `Syscall12` | Use [SyscallN] instead. |
| `syscall` | `Syscall15` | Use [SyscallN] instead. |
| `syscall` | `Syscall18` | Use [SyscallN] instead. |
| `syscall` | `Syscall6` | Use [SyscallN] instead. |
| `syscall` | `Syscall9` | Use [SyscallN] instead. |

## 修補版本

| 版本 | 發布日期 | 含安全修補 | 內容（官方原文） |
| --- | --- | --- | --- |
| `go1.18.1` | 2022-04-12 | 是 | includes security fixes to the crypto/elliptic, crypto/x509, and encoding/pem packages, as well as bug fixes to the compiler, linker, runtime, the go command, vet, and the bytes, crypto/x509, and go/types packages. |
| `go1.18.2` | 2022-05-10 | 是 | includes security fixes to the syscall package, as well as bug fixes to the compiler, runtime, the go command, and the crypto/x509, go/types, net/http/httptest, reflect, and sync/atomic packages. |
| `go1.18.3` | 2022-06-01 | 是 | includes security fixes to the crypto/rand, crypto/tls, os/exec, and path/filepath packages, as well as bug fixes to the compiler, and the crypto/tls and text/template/parse packages. |
| `go1.18.4` | 2022-07-12 | 是 | includes security fixes to the compress/gzip, encoding/gob, encoding/xml, go/parser, io/fs, net/http, and path/filepath packages, as well as bug fixes to the compiler, the go command, the linker, the runtime, and the runtime/metrics package. |
| `go1.18.5` | 2022-08-01 | 是 | includes security fixes to the encoding/gob and math/big packages, as well as bug fixes to the compiler, the go command, the runtime, and the testing package. |
| `go1.18.6` | 2022-09-06 | 是 | includes security fixes to the net/http package, as well as bug fixes to the compiler, the go command, the pprof command, the runtime, and the crypto/tls, encoding/xml, and net packages. |
| `go1.18.7` | 2022-10-04 | 是 | includes security fixes to the archive/tar, net/http/httputil, and regexp packages, as well as bug fixes to the compiler, the linker, and the go/types package. |
| `go1.18.8` | 2022-11-01 | 是 | includes security fixes to the os/exec and syscall packages, as well as bug fixes to the runtime. |
| `go1.18.9` | 2022-12-06 | 是 | includes security fixes to the net/http and os packages, as well as bug fixes to cgo, the compiler, the runtime, and the crypto/x509 and os/exec packages. |
| `go1.18.10` | 2023-01-10 | 否 | includes fixes to cgo, the compiler, the linker, and the crypto/x509, net/http, and syscall packages. |

## 已知漏洞

在 Go 1.18 系列修補版中修正的漏洞共 25 個；仍影響最新修補版 `go1.18.10` 的漏洞共 142 個。

### 本系列已修正

| 編號 | CVE | 摘要（官方原文） | 修正於 |
| --- | --- | --- | --- |
| [GO-2022-1144](https://pkg.go.dev/vuln/GO-2022-1144) | CVE-2022-41717 | Excessive memory growth in net/http and golang.org/x/net/http2 | go1.18.9、go1.19.4 |
| [GO-2022-1143](https://pkg.go.dev/vuln/GO-2022-1143) | CVE-2022-41720 | Restricted file access on Windows in os and net/http | go1.18.9、go1.19.4 |
| [GO-2022-1095](https://pkg.go.dev/vuln/GO-2022-1095) | CVE-2022-41716 | Unsanitized NUL in environment variables on Windows in syscall and os/exec | go1.18.8、go1.19.3 |
| [GO-2022-1039](https://pkg.go.dev/vuln/GO-2022-1039) | CVE-2022-41715 | Memory exhaustion when compiling regular expressions in regexp/syntax | go1.18.7、go1.19.2 |
| [GO-2022-1038](https://pkg.go.dev/vuln/GO-2022-1038) | CVE-2022-2880 | Incorrect sanitization of forwarded query parameters in net/http/httputil | go1.18.7、go1.19.2 |
| [GO-2022-1037](https://pkg.go.dev/vuln/GO-2022-1037) | CVE-2022-2879 | Unbounded memory consumption when reading headers in archive/tar | go1.18.7、go1.19.2 |
| [GO-2022-0969](https://pkg.go.dev/vuln/GO-2022-0969) | CVE-2022-27664 | Denial of service in net/http and golang.org/x/net/http2 | go1.18.6、go1.19.1 |
| [GO-2022-0537](https://pkg.go.dev/vuln/GO-2022-0537) | CVE-2022-32189 | Panic when decoding Float and Rat types in math/big | go1.17.13、go1.18.5 |
| [GO-2022-0533](https://pkg.go.dev/vuln/GO-2022-0533) | CVE-2022-29804 | Path traversal via Clean on Windows in path/filepath | go1.17.11、go1.18.3 |
| [GO-2022-0532](https://pkg.go.dev/vuln/GO-2022-0532) | CVE-2022-30580 | Empty Cmd.Path can trigger unintended binary in os/exec on Windows | go1.17.11、go1.18.3 |
| [GO-2022-0531](https://pkg.go.dev/vuln/GO-2022-0531) | CVE-2022-30629 | Session tickets lack random ticket_age_add in crypto/tls | go1.17.11、go1.18.3 |
| [GO-2022-0527](https://pkg.go.dev/vuln/GO-2022-0527) | CVE-2022-30630 | Stack exhaustion in Glob on certain paths in io/fs | go1.17.12、go1.18.4 |
| [GO-2022-0526](https://pkg.go.dev/vuln/GO-2022-0526) | CVE-2022-30635 | Stack exhaustion when decoding certain messages in encoding/gob | go1.17.12、go1.18.4 |
| [GO-2022-0525](https://pkg.go.dev/vuln/GO-2022-0525) | CVE-2022-1705 | Improper sanitization of Transfer-Encoding headers in net/http | go1.17.12、go1.18.4 |
| [GO-2022-0524](https://pkg.go.dev/vuln/GO-2022-0524) | CVE-2022-30631 | Stack exhaustion when reading certain archives in compress/gzip | go1.17.12、go1.18.4 |
| [GO-2022-0523](https://pkg.go.dev/vuln/GO-2022-0523) | CVE-2022-30633 | Stack exhaustion when unmarshaling certain documents in encoding/xml | go1.17.12、go1.18.4 |
| [GO-2022-0522](https://pkg.go.dev/vuln/GO-2022-0522) | CVE-2022-30632 | Stack exhaustion on crafted paths in path/filepath | go1.17.12、go1.18.4 |
| [GO-2022-0521](https://pkg.go.dev/vuln/GO-2022-0521) | CVE-2022-28131 | Stack exhaustion from deeply nested XML documents in encoding/xml | go1.17.12、go1.18.4 |
| [GO-2022-0520](https://pkg.go.dev/vuln/GO-2022-0520) | CVE-2022-32148 | Exposure of client IP addresses in net/http | go1.17.12、go1.18.4 |
| [GO-2022-0515](https://pkg.go.dev/vuln/GO-2022-0515) | CVE-2022-1962 | Stack exhaustion due to deeply nested types in go/parser | go1.17.12、go1.18.4 |
| [GO-2022-0493](https://pkg.go.dev/vuln/GO-2022-0493) | CVE-2022-29526 | Incorrect privilege reporting in syscall and golang.org/x/sys/unix | go1.17.10、go1.18.2 |
| [GO-2022-0477](https://pkg.go.dev/vuln/GO-2022-0477) | CVE-2022-30634 | Indefinite hang with large buffers on Windows in crypto/rand | go1.17.11、go1.18.3 |
| [GO-2022-0435](https://pkg.go.dev/vuln/GO-2022-0435) | CVE-2022-28327 | Panic due to large inputs affecting P-256 curves in crypto/elliptic | go1.17.9、go1.18.1 |
| [GO-2022-0434](https://pkg.go.dev/vuln/GO-2022-0434) | CVE-2022-27536 | Panic during certificate parsing on Darwin in crypto/x509 | go1.18.1 |
| [GO-2022-0433](https://pkg.go.dev/vuln/GO-2022-0433) | CVE-2022-24675 | Stack overflow from a large amount of PEM data in encoding/pem | go1.17.9、go1.18.1 |

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


## 資料來源

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