Go 1.0

最後更新


Go 1.0 發布於 2012-03-28,目前最新修補版為 go1.0.3,已停止支援,請升級到 go1.27.4。

版本介紹


Go 1 是 Go 第一個正式穩定版本。它最重要的意義是「Go 1 相容性承諾(compatibility promise)」:照 Go 1 規格寫的程式,在之後所有 Go 1.x 版本都應該能繼續編譯、執行。為了換到這份長期穩定,Go 1 趁發布前一次清掉了許多不一致的設計,並提供 go fix 工具協助舊程式自動升級。

語言變更


  • 新增內建的 error 介面型別,成為整個語言回報錯誤的統一方式,原本的 os.Error 被取代。
  • 新增 rune 型別(int32 的別名),專門表示一個 Unicode 碼位,range 字串時取到的就是 rune。
  • 新增內建函式 delete(m, k) 刪除映射(map)中的鍵,取代舊的 m[k] = v, false 寫法。
  • 結構(struct)與陣列可以用 ==、!= 比較,因此可以當作映射的鍵;函式與映射則不再能互相比較(只能和 nil 比)。
  • 規格明定映射的 for range 走訪順序不可預期,避免程式依賴特定順序。
  • append 可以把字串直接接到 []byte 後面;套件的 init 中也可以啟動 goroutine。

工具


  • 推出 go 命令,負責下載、建置、安裝套件,不再需要 Makefile;依賴關係直接從原始碼的 import 推導。
  • go fix 可自動把 Go 1 之前(r60)的程式改寫成新的 API。

標準庫重點


  • 套件重新整理成階層式路徑,例如 http 變成 net/http、json 變成 encoding/json、utf8 變成 unicode/utf8。
  • 新增 errors 套件,用 errors.New 建立簡單的錯誤值。
  • time 套件全面重新設計:time.Time 表示一個時間點,time.Duration 表示一段時間長度,取代過去用 int64 奈秒表示一切的做法。
  • 不夠成熟的套件移到 exp、old 或子儲存庫(subrepository),讓標準庫只留下願意長期維護的部分。

結構相等與 delete


Go 1 起結構可以比較,所以能直接拿來當映射的鍵;刪除映射元素則用內建的 delete。
  1. package main
  2. import "fmt"
  3. type Point struct {
  4. X, Y int
  5. }
  6. func main() {
  7. visited := map[Point]bool{
  8. {1, 2}: true,
  9. {3, 4}: true,
  10. }
  11. fmt.Println(Point{1, 2} == Point{1, 2})
  12. fmt.Println(visited[Point{3, 4}])
  13. delete(visited, Point{3, 4})
  14. fmt.Println(len(visited), visited[Point{3, 4}])
  15. }

  1. true
  2. true
  3. 1 false

error、rune 與新的 time


這三個 Go 1 的新設計至今仍是日常寫 Go 的基礎:函式用 error 回報失敗、range 字串得到 rune、時間用 Time 與 Duration 計算。
  1. package main
  2. import (
  3. "errors"
  4. "fmt"
  5. "time"
  6. )
  7. func divide(a, b int) (int, error) {
  8. if b == 0 {
  9. return 0, errors.New("divide by zero")
  10. }
  11. return a / b, nil
  12. }
  13. func main() {
  14. if _, err := divide(1, 0); err != nil {
  15. fmt.Println("error:", err)
  16. }
  17. start := time.Date(2012, 3, 28, 9, 0, 0, 0, time.UTC)
  18. end := start.Add(90 * time.Minute)
  19. fmt.Println(end.Format("2006-01-02 15:04"))
  20. fmt.Println(end.Sub(start))
  21. for i, r := range "Go語言" {
  22. fmt.Printf("%d:%c ", i, r)
  23. }
  24. fmt.Println()
  25. }

  1. error: divide by zero
  2. 2012-03-28 10:30
  3. 1h30m0s
  4. 0:G 1:o 2:語 5:言

本版新增的棄用 API


本版沒有新增棄用 API。

修補版本


版本發布日期含安全修補內容(官方原文)
go1.0.12012-04-25否was issued to fix an escape analysis bug that can lead to memory corruption. It also includes several minor code and documentation fixes.
go1.0.22012-06-13否was issued to fix two bugs in the implementation of maps using struct or array keys: issue 3695 and issue 3573. It also includes many minor code and documentation fixes.
go1.0.32012-09-21否includes minor code and documentation fixes.

已知漏洞


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

資料來源