型別斷言與型別 switch

最後更新


值放進介面後,編譯器只知道它是「某個介面」;本頁說明如何用型別斷言 x.(T)、comma ok 寫法與型別 switch switch x.(type),把介面裡的具體型別取回來。

為什麼需要型別斷言


介面值由動態型別與動態值組成,見介面值與 nil。透過介面只能呼叫介面宣告的方法;如果你想用具體型別的欄位、其他方法,或對 any 裡的數字做運算,就要先問:「盒子裡到底是什麼?」
型別斷言(type assertion)就是這個提問。它只能用在介面型別的值上,對一般具體型別的變數使用會編譯失敗。
寫法失敗時用途
v := x.(T)panic確定一定是 T
v, ok := x.(T)ok 為 false,v 為 T 的零值不確定,想安全檢查
switch v := x.(type)走 default依型別分成多種處理

x.(T) 取出具體型別


x.(T) 斷言介面 x 裡裝的是型別 T。成功時回傳型別為 T 的值,之後就能使用 T 的所有欄位與方法。
範例:
  1. package main
  2. import "fmt"
  3. type Dog struct {
  4. Name string
  5. Breed string
  6. }
  7. func (d Dog) Sound() string { return "汪" }
  8. type Animal interface {
  9. Sound() string
  10. }
  11. func main() {
  12. var a Animal = Dog{Name: "小黑", Breed: "柴犬"}
  13. fmt.Println("介面只能叫:", a.Sound())
  14. d := a.(Dog)
  15. fmt.Println("斷言後取得欄位:", d.Name, d.Breed)
  16. var v any = 40
  17. n := v.(int)
  18. fmt.Println("any 裡的數字加 2:", n+2)
  19. }

輸出:
  1. 介面只能叫: 汪
  2. 斷言後取得欄位: 小黑 柴犬
  3. any 裡的數字加 2: 42

斷言失敗會 panic


注意:單一回傳值的 x.(T) 如果型別不符,或 x 是 nil 介面,會直接 panic,訊息類似 interface conversion: interface {} is string, not int。只在你百分之百確定型別時才這樣寫。
範例用 recover 攔下 panic 觀察訊息,見panic 與 recover。
範例:
  1. package main
  2. import "fmt"
  3. func mustInt(v any) (n int) {
  4. defer func() {
  5. if r := recover(); r != nil {
  6. fmt.Println("panic:", r)
  7. n = -1
  8. }
  9. }()
  10. return v.(int)
  11. }
  12. func main() {
  13. fmt.Println(mustInt(7))
  14. fmt.Println(mustInt("7"))
  15. fmt.Println(mustInt(nil))
  16. }

輸出:
  1. 7
  2. panic: interface conversion: interface {} is string, not int
  3. -1
  4. panic: interface conversion: interface {} is nil, not int
  5. -1

comma ok 安全檢查


多接一個布林值 ok,斷言失敗時就不會 panic:ok 為 false,第一個值是 T 的零值。這是處理「不確定型別」的標準寫法,和映射查詢的 v, ok := m[k] 是同一種慣例。
範例:
  1. package main
  2. import "fmt"
  3. func main() {
  4. inputs := []any{"hello", 42, nil, "go"}
  5. for _, v := range inputs {
  6. if s, ok := v.(string); ok {
  7. fmt.Printf("字串 %q,長度 %d\n", s, len(s))
  8. } else {
  9. fmt.Printf("不是字串:%v,s 為零值 %q\n", v, s)
  10. }
  11. }
  12. }

輸出:
  1. 字串 "hello",長度 5
  2. 不是字串:42,s 為零值 ""
  3. 不是字串:<nil>,s 為零值 ""
  4. 字串 "go",長度 2

斷言成另一個介面


T 也可以是介面型別。此時斷言的問題變成:「盒子裡的值有沒有實作這個介面?」成功時得到的是新介面型別的值。
這常用來檢查「選用能力(optional capability)」:函式只要求最基本的介面,但如果傳進來的值剛好有更多能力,就使用它。標準庫大量使用這招,例如 io.Copy 會檢查來源是否實作 io.WriterTo。
範例:
  1. package main
  2. import "fmt"
  3. type Shape interface {
  4. Area() float64
  5. }
  6. type Namer interface {
  7. Name() string
  8. }
  9. type Square struct{ S float64 }
  10. func (s Square) Area() float64 { return s.S * s.S }
  11. func (s Square) Name() string { return "正方形" }
  12. type Blob struct{ A float64 }
  13. func (b Blob) Area() float64 { return b.A }
  14. func report(s Shape) {
  15. name := "未命名圖形"
  16. if n, ok := s.(Namer); ok {
  17. name = n.Name()
  18. }
  19. fmt.Printf("%s 面積 %.1f\n", name, s.Area())
  20. }
  21. func main() {
  22. report(Square{S: 3})
  23. report(Blob{A: 7.5})
  24. }

輸出:
  1. 正方形 面積 9.0
  2. 未命名圖形 面積 7.5

型別 switch


switch x.(type) 依型別分支


當可能的型別不只一兩種,連續寫 comma ok 會很冗長。型別 switch(type switch)用 switch v := x.(type) 一次比對多種型別,每個 case 寫一個型別。.(type) 只能用在 switch 裡。
在單一型別的 case 中,v 的型別就是該 case 的型別,可以直接使用。switch 的一般用法見if 與 switch。
範例:
  1. package main
  2. import "fmt"
  3. func describe(x any) string {
  4. switch v := x.(type) {
  5. case int:
  6. return fmt.Sprintf("整數,平方是 %d", v*v)
  7. case string:
  8. return fmt.Sprintf("字串,共 %d 個位元組", len(v))
  9. case []int:
  10. return fmt.Sprintf("整數切片,共 %d 個元素", len(v))
  11. case error:
  12. return "錯誤: " + v.Error()
  13. default:
  14. return fmt.Sprintf("其他型別 %T", v)
  15. }
  16. }
  17. func main() {
  18. values := []any{5, "Gopher", []int{1, 2, 3}, fmt.Errorf("連線失敗"), 2.5}
  19. for _, v := range values {
  20. fmt.Println(describe(v))
  21. }
  22. }

輸出:
  1. 整數,平方是 25
  2. 字串,共 6 個位元組
  3. 整數切片,共 3 個元素
  4. 錯誤: 連線失敗
  5. 其他型別 float64

多型別 case、nil 與 default


一個 case 可以列多個型別,用逗號分隔。注意:這時 v 的型別維持原本的介面型別(這裡是 any),因為編譯器無法確定是哪一個。
case nil 匹配 nil 介面值;default 匹配其他所有情況。case 依序比對,第一個符合的就執行,所以介面型別的 case(如 fmt.Stringer)要放在可能被它涵蓋的具體型別之後。
範例:
  1. package main
  2. import "fmt"
  3. type Celsius float64
  4. func (c Celsius) String() string { return fmt.Sprintf("%.1f°C", float64(c)) }
  5. func kind(x any) string {
  6. switch v := x.(type) {
  7. case nil:
  8. return "nil 介面"
  9. case int, int64:
  10. return fmt.Sprintf("整數家族 %T,v 的靜態型別仍是 any: %v", v, v)
  11. case fmt.Stringer:
  12. return "可轉字串: " + v.String()
  13. default:
  14. return fmt.Sprintf("其他 %T", v)
  15. }
  16. }
  17. func main() {
  18. for _, x := range []any{nil, 3, int64(9), Celsius(36.6), true} {
  19. fmt.Println(kind(x))
  20. }
  21. }

輸出:
  1. nil 介面
  2. 整數家族 int,v 的靜態型別仍是 any: 3
  3. 整數家族 int64,v 的靜態型別仍是 any: 9
  4. 可轉字串: 36.6°C
  5. 其他 bool

什麼時候用


錯誤處理優先用 errors.As


錯誤經過 fmt.Errorf("...: %w", err) 包裝後,外層的動態型別已經不是原本的錯誤型別,直接型別斷言會失敗。檢查錯誤型別時應該用 errors.As,它會沿著包裝鏈逐層尋找,詳見錯誤包裝。
範例:
  1. package main
  2. import (
  3. "errors"
  4. "fmt"
  5. )
  6. type NotFoundError struct {
  7. Key string
  8. }
  9. func (e *NotFoundError) Error() string { return "找不到 " + e.Key }
  10. func load(key string) error {
  11. return fmt.Errorf("load 設定: %w", &NotFoundError{Key: key})
  12. }
  13. func main() {
  14. err := load("port")
  15. _, ok := err.(*NotFoundError)
  16. fmt.Println("直接型別斷言:", ok)
  17. var nf *NotFoundError
  18. if errors.As(err, &nf) {
  19. fmt.Println("errors.As 找到:", nf.Key)
  20. }
  21. }

輸出:
  1. 直接型別斷言: false
  2. errors.As 找到: port

型別斷言不宜濫用:如果程式到處都在 switch x.(type),通常代表應該把共通行為抽成介面方法,讓每個型別自己實作,而不是由呼叫端逐一判斷。

重點整理


  • 型別斷言只能用在介面值上,用來取回動態型別
  • x.(T) 失敗會 panic;v, ok := x.(T) 失敗時 ok 為 false、v 為零值
  • T 可以是介面,用來檢查值是否具備額外能力
  • switch v := x.(type) 一次處理多種型別;多型別 case 中 v 維持原介面型別
  • case nil 匹配 nil 介面,case 依序比對
  • 檢查被包裝的錯誤型別用 errors.As,不用型別斷言

資料來源