Go 1.1

最後更新


Go 1.1 發布於 2013-05-13,目前最新修補版為 go1.1.2,已停止支援,請升級到 go1.27.4。

版本介紹


Go 1.1 是 Go 1 之後第一個大改版,主軸是效能:官方測試中多數程式只要重新編譯就快了約 30%–40%。語言上加入了「方法值(method value)」,工具上則首次內建競態偵測器(race detector),從此並行程式的資料競爭(data race)可以用 -race 自動抓出來。

語言變更


  • 新增方法值:x.Method 可以當成一個已綁定接收者(receiver)的函式值傳來傳去。
  • 放寬結尾 return 規則:只要函式最後一個敘述必定不會往下執行(例如無條件的 for 迴圈、兩邊都 return 的 if-else),就不必再補 return。
  • 除以常數 0 的整數運算改為編譯錯誤,不再等到執行時才 panic。
  • Unicode 代理字元(surrogate half)不再是合法的 rune 或字串常數。

工具


  • 新增競態偵測器,以 go test -race、go build -race 啟用。
  • go test 新增 -blockprofile,分析 goroutine 卡在哪裡等待;開啟效能分析時會保留測試執行檔方便後續分析。

執行時與效能


  • 在 64 位元平台上 int、uint 改為 64 位元,切片可以超過 20 億個元素。
  • 64 位元平台的堆積(heap)上限從數 GB 提高到數十 GB。
  • 新的映射實作大幅降低記憶體與 CPU 用量;垃圾回收(GC)更平行、更精確。
  • 執行時與網路函式庫整合得更緊密,網路操作需要的執行緒切換更少。

標準庫重點


  • bufio 新增 Scanner,用簡單的迴圈逐行或逐字讀取輸入。
  • 新增 go/format(以程式呼叫 gofmt 的格式化)與 net/http/cookiejar(管理 HTTP cookie)。
  • reflect 新增 Select、MakeFunc、Value.Convert 等能力。
  • time 在 Linux、macOS 等系統上提升到奈秒精度,並新增 Round、Truncate 方法。

方法值


把 c.Inc 存進變數後,它就「記住」了 c,之後呼叫時不必再提供接收者。
  1. package main
  2. import (
  3. "fmt"
  4. "strings"
  5. )
  6. type Counter struct {
  7. n int
  8. }
  9. func (c *Counter) Inc() {
  10. c.n++
  11. }
  12. func repeat(times int, f func()) {
  13. for i := 0; i < times; i++ {
  14. f()
  15. }
  16. }
  17. func main() {
  18. c := &Counter{}
  19. inc := c.Inc
  20. repeat(3, inc)
  21. fmt.Println(c.n)
  22. upper := strings.ToUpper
  23. fmt.Println(upper("method value"))
  24. }

  1. 3
  2. METHOD VALUE

bufio.Scanner


Scanner 預設逐行切割並去掉換行字元;換成 bufio.ScanWords 就能逐字讀取。讀完後記得檢查 Err()。
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "strings"
  6. )
  7. func main() {
  8. input := "first line\nsecond line\nthird line\n"
  9. scanner := bufio.NewScanner(strings.NewReader(input))
  10. n := 0
  11. for scanner.Scan() {
  12. n++
  13. fmt.Printf("%d: %s\n", n, scanner.Text())
  14. }
  15. if err := scanner.Err(); err != nil {
  16. fmt.Println("error:", err)
  17. }
  18. words := bufio.NewScanner(strings.NewReader("go is fun"))
  19. words.Split(bufio.ScanWords)
  20. count := 0
  21. for words.Scan() {
  22. count++
  23. }
  24. fmt.Println("words:", count)
  25. }

  1. 1: first line
  2. 2: second line
  3. 3: third line
  4. words: 3

本版新增的棄用 API


本版沒有新增棄用 API。

修補版本


版本發布日期含安全修補內容(官方原文)
go1.1.12013-06-13是includes a security fix to the compiler and several bug fixes to the compiler and runtime.
go1.1.22013-08-13否includes fixes to the gc compiler and cgo, and the bufio, runtime, syscall, and time packages.

已知漏洞


在 Go 1.1 系列修補版中修正的漏洞共 0 個;仍影響最新修補版 go1.1.2 的漏洞共 214 個。
本版已停止支援,不會再修正這些漏洞;完整清單見 資安漏洞。

資料來源