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,詳見 泛型函式。
  • 介面可以列出型別集合(type set),例如 ~int | ~float64,當作型別參數的約束(constraint);~int 表示「底層型別是 int 的所有型別」。
  • 新增預先宣告的 any,它就是 interface{} 的別名,寫起來更短。
  • 新增預先宣告的 comparable 約束,代表可以用 == 比較的型別,常用在映射的鍵。

工具


  • go test -fuzz 內建模糊測試:自動產生大量隨機輸入找出會讓程式出錯的案例,詳見 模糊測試。
  • 新增 go work 工作區模式,用 go.work 同時開發多個本機模組,不必改 go.mod,詳見 工作區。
  • 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 則示範兩個型別參數。
範例:
  1. package main
  2. import "fmt"
  3. type Number interface {
  4. ~int | ~int64 | ~float64
  5. }
  6. func Sum[T Number](values []T) T {
  7. var total T
  8. for _, v := range values {
  9. total += v
  10. }
  11. return total
  12. }
  13. func Map[T, U any](values []T, f func(T) U) []U {
  14. out := make([]U, 0, len(values))
  15. for _, v := range values {
  16. out = append(out, f(v))
  17. }
  18. return out
  19. }
  20. func main() {
  21. fmt.Println(Sum([]int{1, 2, 3}))
  22. fmt.Println(Sum([]float64{1.5, 2.25}))
  23. words := Map([]int{1, 2, 3}, func(n int) string {
  24. return fmt.Sprintf("#%d", n)
  25. })
  26. fmt.Println(words)
  27. }

輸出:
  1. 6
  2. 3.75
  3. [#1 #2 #3]

泛型型別


型別也可以帶型別參數,寫一次 Stack[T] 就能裝任何型別。使用時要寫出具體型別,例如 Stack[string];var zero T 取得該型別的零值,常用來在「沒有資料」時回傳。詳見 泛型型別。
範例:
  1. package main
  2. import "fmt"
  3. type Stack[T any] struct {
  4. items []T
  5. }
  6. func (s *Stack[T]) Push(v T) {
  7. s.items = append(s.items, v)
  8. }
  9. func (s *Stack[T]) Pop() (T, bool) {
  10. var zero T
  11. if len(s.items) == 0 {
  12. return zero, false
  13. }
  14. last := s.items[len(s.items)-1]
  15. s.items = s.items[:len(s.items)-1]
  16. return last, true
  17. }
  18. func main() {
  19. var s Stack[string]
  20. s.Push("a")
  21. s.Push("b")
  22. v, ok := s.Pop()
  23. fmt.Println(v, ok)
  24. v, ok = s.Pop()
  25. fmt.Println(v, ok)
  26. v, ok = s.Pop()
  27. fmt.Printf("%q %v\n", v, ok)
  28. }

輸出:
  1. b true
  2. a true
  3. "" false

net/netip


舊的 net.IP 是位元組切片,不能直接當映射的鍵,也不能用 == 比較。netip.Addr 是小巧的值型別,可以比較、可以當鍵,解析失敗時回傳錯誤。Prefix 表示網段,Contains 判斷位址是否在網段內。詳見 net/netip。
範例:
  1. package main
  2. import (
  3. "fmt"
  4. "net/netip"
  5. )
  6. func main() {
  7. addr, err := netip.ParseAddr("192.168.1.10")
  8. if err != nil {
  9. fmt.Println("error:", err)
  10. return
  11. }
  12. prefix := netip.MustParsePrefix("192.168.1.0/24")
  13. fmt.Println(addr, addr.Is4(), prefix.Contains(addr))
  14. seen := map[netip.Addr]bool{addr: true}
  15. other := netip.MustParseAddr("192.168.1.10")
  16. fmt.Println(seen[other])
  17. _, err = netip.ParseAddr("300.1.1.1")
  18. fmt.Println(err != nil)
  19. }

輸出:
  1. 192.168.1.10 true true
  2. true
  3. true

strings.Cut


以前要切開 key=value 常寫 strings.Index 再自己算切片範圍,容易寫錯。strings.Cut 回傳分隔符號前、後兩段,以及是否找到;找不到時 before 是原字串、after 是空字串。
範例:
  1. package main
  2. import (
  3. "fmt"
  4. "strings"
  5. )
  6. func main() {
  7. key, value, found := strings.Cut("name=gopher", "=")
  8. fmt.Println(key, value, found)
  9. key, value, found = strings.Cut("no-separator", "=")
  10. fmt.Printf("%q %q %v\n", key, value, found)
  11. }

輸出:
  1. name gopher true
  2. "no-separator" "" false

本版新增的棄用 API


以下 API 從 Go 1.18 起標記為棄用(Deprecated),新程式不要再使用;說明欄為官方原文。
套件符號官方說明
bytesTitleThe rule Title uses for word boundaries does not handle Unicode punctuation properly. Use golang.org/x/text/cases instead.
crypto/tlsConfig.PreferServerCipherSuitesPreferServerCipherSuites is ignored.
crypto/x509CertPool.Subjectsif s was returned by [SystemCertPool], Subjects will not include the system roots.
go/typesInterface.EmbeddedUse [Interface.EmbeddedType] which is not restricted to defined (*[Named]) types.
go/typesNewInterfaceUse NewInterfaceType instead which allows arbitrary embedded types.
go/typesNewSignatureUse [NewSignatureType] instead which allows for type parameters.
netError.TemporaryTemporary errors are not well-defined. Most "temporary" errors are timeouts, and the few exceptions are surprising. Do not use this method.
stringsTitleThe rule Title uses for word boundaries does not handle Unicode punctuation properly. Use golang.org/x/text/cases instead.
syscallSyscallUse [SyscallN] instead.
syscallSyscall12Use [SyscallN] instead.
syscallSyscall15Use [SyscallN] instead.
syscallSyscall18Use [SyscallN] instead.
syscallSyscall6Use [SyscallN] instead.
syscallSyscall9Use [SyscallN] instead.

修補版本


版本發布日期含安全修補內容(官方原文)
go1.18.12022-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.22022-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.32022-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.42022-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.52022-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.62022-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.72022-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.82022-11-01是includes security fixes to the os/exec and syscall packages, as well as bug fixes to the runtime.
go1.18.92022-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.102023-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-1144CVE-2022-41717Excessive memory growth in net/http and golang.org/x/net/http2go1.18.9、go1.19.4
GO-2022-1143CVE-2022-41720Restricted file access on Windows in os and net/httpgo1.18.9、go1.19.4
GO-2022-1095CVE-2022-41716Unsanitized NUL in environment variables on Windows in syscall and os/execgo1.18.8、go1.19.3
GO-2022-1039CVE-2022-41715Memory exhaustion when compiling regular expressions in regexp/syntaxgo1.18.7、go1.19.2
GO-2022-1038CVE-2022-2880Incorrect sanitization of forwarded query parameters in net/http/httputilgo1.18.7、go1.19.2
GO-2022-1037CVE-2022-2879Unbounded memory consumption when reading headers in archive/targo1.18.7、go1.19.2
GO-2022-0969CVE-2022-27664Denial of service in net/http and golang.org/x/net/http2go1.18.6、go1.19.1
GO-2022-0537CVE-2022-32189Panic when decoding Float and Rat types in math/biggo1.17.13、go1.18.5
GO-2022-0533CVE-2022-29804Path traversal via Clean on Windows in path/filepathgo1.17.11、go1.18.3
GO-2022-0532CVE-2022-30580Empty Cmd.Path can trigger unintended binary in os/exec on Windowsgo1.17.11、go1.18.3
GO-2022-0531CVE-2022-30629Session tickets lack random ticket_age_add in crypto/tlsgo1.17.11、go1.18.3
GO-2022-0527CVE-2022-30630Stack exhaustion in Glob on certain paths in io/fsgo1.17.12、go1.18.4
GO-2022-0526CVE-2022-30635Stack exhaustion when decoding certain messages in encoding/gobgo1.17.12、go1.18.4
GO-2022-0525CVE-2022-1705Improper sanitization of Transfer-Encoding headers in net/httpgo1.17.12、go1.18.4
GO-2022-0524CVE-2022-30631Stack exhaustion when reading certain archives in compress/gzipgo1.17.12、go1.18.4
GO-2022-0523CVE-2022-30633Stack exhaustion when unmarshaling certain documents in encoding/xmlgo1.17.12、go1.18.4
GO-2022-0522CVE-2022-30632Stack exhaustion on crafted paths in path/filepathgo1.17.12、go1.18.4
GO-2022-0521CVE-2022-28131Stack exhaustion from deeply nested XML documents in encoding/xmlgo1.17.12、go1.18.4
GO-2022-0520CVE-2022-32148Exposure of client IP addresses in net/httpgo1.17.12、go1.18.4
GO-2022-0515CVE-2022-1962Stack exhaustion due to deeply nested types in go/parsergo1.17.12、go1.18.4
GO-2022-0493CVE-2022-29526Incorrect privilege reporting in syscall and golang.org/x/sys/unixgo1.17.10、go1.18.2
GO-2022-0477CVE-2022-30634Indefinite hang with large buffers on Windows in crypto/randgo1.17.11、go1.18.3
GO-2022-0435CVE-2022-28327Panic due to large inputs affecting P-256 curves in crypto/ellipticgo1.17.9、go1.18.1
GO-2022-0434CVE-2022-27536Panic during certificate parsing on Darwin in crypto/x509go1.18.1
GO-2022-0433CVE-2022-24675Stack overflow from a large amount of PEM data in encoding/pemgo1.17.9、go1.18.1

本版已停止支援,不會再修正這些漏洞;完整清單見 資安漏洞。

資料來源