型別斷言與型別 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 的所有欄位與方法。範例:
- package main
- import "fmt"
- type Dog struct {
- Name string
- Breed string
- }
- func (d Dog) Sound() string { return "汪" }
- type Animal interface {
- Sound() string
- }
- func main() {
- var a Animal = Dog{Name: "小黑", Breed: "柴犬"}
- fmt.Println("介面只能叫:", a.Sound())
- d := a.(Dog)
- fmt.Println("斷言後取得欄位:", d.Name, d.Breed)
- var v any = 40
- n := v.(int)
- fmt.Println("any 裡的數字加 2:", n+2)
- }
輸出:
- 介面只能叫: 汪
- 斷言後取得欄位: 小黑 柴犬
- any 裡的數字加 2: 42
斷言失敗會 panic
注意:單一回傳值的
x.(T) 如果型別不符,或 x 是 nil 介面,會直接 panic,訊息類似 interface conversion: interface {} is string, not int。只在你百分之百確定型別時才這樣寫。範例用
recover 攔下 panic 觀察訊息,見panic 與 recover。範例:
- package main
- import "fmt"
- func mustInt(v any) (n int) {
- defer func() {
- if r := recover(); r != nil {
- fmt.Println("panic:", r)
- n = -1
- }
- }()
- return v.(int)
- }
- func main() {
- fmt.Println(mustInt(7))
- fmt.Println(mustInt("7"))
- fmt.Println(mustInt(nil))
- }
輸出:
- 7
- panic: interface conversion: interface {} is string, not int
- -1
- panic: interface conversion: interface {} is nil, not int
- -1
comma ok 安全檢查
多接一個布林值
ok,斷言失敗時就不會 panic:ok 為 false,第一個值是 T 的零值。這是處理「不確定型別」的標準寫法,和映射查詢的 v, ok := m[k] 是同一種慣例。範例:
- package main
- import "fmt"
- func main() {
- inputs := []any{"hello", 42, nil, "go"}
- for _, v := range inputs {
- if s, ok := v.(string); ok {
- fmt.Printf("字串 %q,長度 %d\n", s, len(s))
- } else {
- fmt.Printf("不是字串:%v,s 為零值 %q\n", v, s)
- }
- }
- }
輸出:
- 字串 "hello",長度 5
- 不是字串:42,s 為零值 ""
- 不是字串:<nil>,s 為零值 ""
- 字串 "go",長度 2
斷言成另一個介面
T 也可以是介面型別。此時斷言的問題變成:「盒子裡的值有沒有實作這個介面?」成功時得到的是新介面型別的值。這常用來檢查「選用能力(optional capability)」:函式只要求最基本的介面,但如果傳進來的值剛好有更多能力,就使用它。標準庫大量使用這招,例如
io.Copy 會檢查來源是否實作 io.WriterTo。範例:
- package main
- import "fmt"
- type Shape interface {
- Area() float64
- }
- type Namer interface {
- Name() string
- }
- type Square struct{ S float64 }
- func (s Square) Area() float64 { return s.S * s.S }
- func (s Square) Name() string { return "正方形" }
- type Blob struct{ A float64 }
- func (b Blob) Area() float64 { return b.A }
- func report(s Shape) {
- name := "未命名圖形"
- if n, ok := s.(Namer); ok {
- name = n.Name()
- }
- fmt.Printf("%s 面積 %.1f\n", name, s.Area())
- }
- func main() {
- report(Square{S: 3})
- report(Blob{A: 7.5})
- }
輸出:
- 正方形 面積 9.0
- 未命名圖形 面積 7.5
型別 switch
switch x.(type) 依型別分支
當可能的型別不只一兩種,連續寫 comma ok 會很冗長。型別 switch(type switch)用
switch v := x.(type) 一次比對多種型別,每個 case 寫一個型別。.(type) 只能用在 switch 裡。在單一型別的
case 中,v 的型別就是該 case 的型別,可以直接使用。switch 的一般用法見if 與 switch。範例:
- package main
- import "fmt"
- func describe(x any) string {
- switch v := x.(type) {
- case int:
- return fmt.Sprintf("整數,平方是 %d", v*v)
- case string:
- return fmt.Sprintf("字串,共 %d 個位元組", len(v))
- case []int:
- return fmt.Sprintf("整數切片,共 %d 個元素", len(v))
- case error:
- return "錯誤: " + v.Error()
- default:
- return fmt.Sprintf("其他型別 %T", v)
- }
- }
- func main() {
- values := []any{5, "Gopher", []int{1, 2, 3}, fmt.Errorf("連線失敗"), 2.5}
- for _, v := range values {
- fmt.Println(describe(v))
- }
- }
輸出:
- 整數,平方是 25
- 字串,共 6 個位元組
- 整數切片,共 3 個元素
- 錯誤: 連線失敗
- 其他型別 float64
多型別 case、nil 與 default
一個
case 可以列多個型別,用逗號分隔。注意:這時 v 的型別維持原本的介面型別(這裡是 any),因為編譯器無法確定是哪一個。case nil 匹配 nil 介面值;default 匹配其他所有情況。case 依序比對,第一個符合的就執行,所以介面型別的 case(如 fmt.Stringer)要放在可能被它涵蓋的具體型別之後。範例:
- package main
- import "fmt"
- type Celsius float64
- func (c Celsius) String() string { return fmt.Sprintf("%.1f°C", float64(c)) }
- func kind(x any) string {
- switch v := x.(type) {
- case nil:
- return "nil 介面"
- case int, int64:
- return fmt.Sprintf("整數家族 %T,v 的靜態型別仍是 any: %v", v, v)
- case fmt.Stringer:
- return "可轉字串: " + v.String()
- default:
- return fmt.Sprintf("其他 %T", v)
- }
- }
- func main() {
- for _, x := range []any{nil, 3, int64(9), Celsius(36.6), true} {
- fmt.Println(kind(x))
- }
- }
輸出:
- nil 介面
- 整數家族 int,v 的靜態型別仍是 any: 3
- 整數家族 int64,v 的靜態型別仍是 any: 9
- 可轉字串: 36.6°C
- 其他 bool
什麼時候用
錯誤處理優先用 errors.As
錯誤經過
fmt.Errorf("...: %w", err) 包裝後,外層的動態型別已經不是原本的錯誤型別,直接型別斷言會失敗。檢查錯誤型別時應該用 errors.As,它會沿著包裝鏈逐層尋找,詳見錯誤包裝。範例:
- package main
- import (
- "errors"
- "fmt"
- )
- type NotFoundError struct {
- Key string
- }
- func (e *NotFoundError) Error() string { return "找不到 " + e.Key }
- func load(key string) error {
- return fmt.Errorf("load 設定: %w", &NotFoundError{Key: key})
- }
- func main() {
- err := load("port")
- _, ok := err.(*NotFoundError)
- fmt.Println("直接型別斷言:", ok)
- var nf *NotFoundError
- if errors.As(err, &nf) {
- fmt.Println("errors.As 找到:", nf.Key)
- }
- }
輸出:
- 直接型別斷言: false
- 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,不用型別斷言