reflect
最後更新
reflect 套件讓程式在執行期間檢查與操作任意值的型別和內容,例如列出結構體的欄位、讀取 struct tag、修改未知型別的變數。這個套件做什麼
一般 Go 程式在編譯時就知道每個變數的型別。但有些程式需要處理「寫程式時還不知道型別」的值,例如:
encoding/json要把任何結構體轉成 JSON,得在執行期找出它有哪些欄位、tag 寫了什麼fmt.Printf("%v", x)要能印出任何型別- ORM、設定檔載入器要把資料填進使用者自訂的結構體
這種「程式檢查自己的結構」的能力叫反射(reflection)。
reflect 的兩個核心型別:| 型別 | 代表 | 取得方式 |
|---|---|---|
reflect.Type | 值的型別資訊(名稱、種類、欄位、方法) | reflect.TypeOf(x)、reflect.TypeFor[T]() |
reflect.Value | 值本身,可讀取、修改、呼叫 | reflect.ValueOf(x) |
另一個重要概念是種類(
Kind):型別可以有無限多種(User、Order...),但種類只有固定幾種(Struct、Int、Slice、Map、Pointer...)。反射程式通常用 Kind 決定怎麼處理。注意:反射比直接操作慢、失去編譯期的型別檢查,用錯方法會在執行期 panic。能用 泛型 或 介面 解決的問題,優先不用反射,見 反射使用建議。概念篇另有 reflect.Type 與 reflect.Value、讀取結構體標籤、透過反射修改值。
匯入
- import "reflect"
常用 API
TypeOf 與 TypeFor
TypeOf(x) 回傳 x 的動態型別。TypeFor[T]()(Go 1.22 起)直接由型別參數取得 Type,不需要先有一個值,特別適合取得介面型別本身(TypeOf 拿到的是介面裡裝的具體型別)。Type 常用方法:Name() 型別名稱(未命名型別如 []int 為空字串)、String() 完整表示、Kind() 種類、Elem() 指標/切片/映射/channel 的元素型別。Kind 印出來時,指標種類(reflect.Pointer)顯示為 ptr。注意:
TypeOf(nil) 回傳 nil。簽名:
- func TypeOf(i any) Type
- func TypeFor[T any]() Type
範例:
- package main
- import (
- "fmt"
- "reflect"
- )
- type User struct {
- Name string
- }
- func main() {
- for _, x := range []any{42, "hi", User{}, &User{}, []int{1}, map[string]bool{}} {
- t := reflect.TypeOf(x)
- fmt.Printf("String=%-16s Name=%-6q Kind=%s\n", t.String(), t.Name(), t.Kind())
- }
- fmt.Println(reflect.TypeOf(&User{}).Elem().Name())
- errType := reflect.TypeFor[error]()
- fmt.Println(errType, errType.Kind())
- fmt.Println(reflect.TypeOf(nil) == nil)
- }
輸出:
- String=int Name="int" Kind=int
- String=string Name="string" Kind=string
- String=main.User Name="User" Kind=struct
- String=*main.User Name="" Kind=ptr
- String=[]int Name="" Kind=slice
- String=map[string]bool Name="" Kind=map
- User
- error interface
- true
ValueOf、Kind 與取值方法
ValueOf(x) 回傳裝著 x 的 Value。依 Kind 呼叫對應的取值方法:Int()(所有有號整數種類)、Uint()、Float()、String()、Bool()、Len()、Index(i)、MapRange() 等。注意:取值方法跟種類不符時會 panic,例如對
Int 種類呼叫 Float()。唯一例外是 String():對非字串種類呼叫時不會 panic,而是回傳 "<int Value>" 這樣的描述字串。簽名:
- func ValueOf(i any) Value
- func (v Value) Kind() Kind
- func (v Value) Int() int64
- func (v Value) Len() int
- func (v Value) Index(i int) Value
範例:
- package main
- import (
- "fmt"
- "reflect"
- )
- func describe(x any) string {
- v := reflect.ValueOf(x)
- switch v.Kind() {
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
- return fmt.Sprintf("整數 %d", v.Int())
- case reflect.String:
- return fmt.Sprintf("字串 %q,長度 %d", v.String(), v.Len())
- case reflect.Slice:
- sum := 0.0
- for i := range v.Len() {
- sum += v.Index(i).Float()
- }
- return fmt.Sprintf("切片,%d 個元素,總和 %.1f", v.Len(), sum)
- default:
- return "其他種類: " + v.Kind().String()
- }
- }
- func main() {
- fmt.Println(describe(int8(7)))
- fmt.Println(describe("Gopher"))
- fmt.Println(describe([]float64{1.5, 2.5, 3}))
- fmt.Println(describe(true))
- fmt.Println(reflect.ValueOf(10).String())
- }
輸出:
- 整數 7
- 字串 "Gopher",長度 6
- 切片,3 個元素,總和 7.0
- 其他種類: bool
- <int Value>
NumField、Field 與 StructTag
對結構體型別,
NumField() 回傳欄位數,Field(i) 回傳第 i 個欄位的 StructField:包含 Name、Type、Tag,以及 IsExported() 判斷是否匯出。Tag 的型別是 StructTag,用 Get(key) 讀取某個鍵的值;Lookup(key) 多回傳一個 bool,分得出「沒有這個鍵」與「值是空字串」。Go 1.26 起,
Type.Fields() 回傳欄位的迭代器,可以直接 for f := range t.Fields()(觀念見 range over func)。注意:對非結構體種類呼叫
NumField、Field、Fields 會 panic。簽名:
- func (tag StructTag) Get(key string) string
- func (tag StructTag) Lookup(key string) (value string, ok bool)
Type 介面中的方法:- NumField() int
- Field(i int) StructField
- Fields() iter.Seq[StructField]
範例:
- package main
- import (
- "fmt"
- "reflect"
- )
- type Product struct {
- ID int `json:"id" db:"product_id"`
- Name string `json:"name"`
- Price float64 `json:"price,omitempty" db:""`
- note string
- }
- func main() {
- t := reflect.TypeFor[Product]()
- fmt.Println("欄位數:", t.NumField())
- for i := range t.NumField() {
- f := t.Field(i)
- fmt.Printf("%-5s %-7s json=%-16q exported=%v\n", f.Name, f.Type, f.Tag.Get("json"), f.IsExported())
- }
- for f := range t.Fields() {
- v, ok := f.Tag.Lookup("db")
- fmt.Printf("%s: db=%q ok=%v\n", f.Name, v, ok)
- }
- }
輸出:
- 欄位數: 4
- ID int json="id" exported=true
- Name string json="name" exported=true
- Price float64 json="price,omitempty" exported=true
- note string json="" exported=false
- ID: db="product_id" ok=true
- Name: db="" ok=false
- Price: db="" ok=true
- note: db="" ok=false
Value.Field、FieldByName 與 Value.Fields
Value 也有欄位方法,但回傳的是欄位的「值」(Value):Field(i) 依位置、FieldByName(name) 依名稱取得。FieldByName 找不到時回傳零值 Value,用 IsValid() 檢查。Go 1.26 起,
Value.Fields() 一次給出欄位描述與欄位值,可以寫 for f, fv := range v.Fields()。Interface() 把 Value 轉回 any,再用型別斷言取得具體型別;Go 1.25 起也可用泛型函式 reflect.TypeAssert[T](v) 一步完成。注意:對未匯出欄位的
Value 呼叫 Interface() 會 panic;可用 CanInterface() 先檢查。簽名:
- func (v Value) Field(i int) Value
- func (v Value) FieldByName(name string) Value
- func (v Value) Fields() iter.Seq2[StructField, Value]
- func (v Value) Interface() (i any)
- func TypeAssert[T any](v Value) (T, bool)
範例:
- package main
- import (
- "fmt"
- "reflect"
- )
- type Config struct {
- Host string
- Port int
- Debug bool
- secrets string
- }
- func main() {
- c := Config{Host: "localhost", Port: 8080, Debug: true, secrets: "x"}
- v := reflect.ValueOf(c)
- for f, fv := range v.Fields() {
- if !fv.CanInterface() {
- fmt.Printf("%s: (未匯出,略過)\n", f.Name)
- continue
- }
- fmt.Printf("%s = %v\n", f.Name, fv.Interface())
- }
- port, ok := reflect.TypeAssert[int](v.FieldByName("Port"))
- fmt.Println(port+1, ok)
- fmt.Println(v.FieldByName("Timeout").IsValid())
- }
輸出:
- Host = localhost
- Port = 8080
- Debug = true
- secrets: (未匯出,略過)
- 8081 true
- false
Elem、CanSet 與 Set
要透過反射修改變數,必須傳入它的指標:
reflect.ValueOf(&x).Elem() 才是「可設定的」(settable)。直接 ValueOf(x) 拿到的只是一份複本,改了也不會影響原變數,所以 Go 直接禁止。Elem():取得指標指向的值(或介面裡裝的值)CanSet():是否可設定;未匯出欄位也不可設定Set(x):以另一個Value設定;也有SetInt、SetString、SetBool等專用版本
注意:對不可設定的
Value 呼叫 Set 系列會 panic;值的型別不能指派給目標時也會 panic。簽名:
- func (v Value) Elem() Value
- func (v Value) CanSet() bool
- func (v Value) Set(x Value)
- func (v Value) SetInt(x int64)
- func (v Value) SetString(x string)
範例:
- package main
- import (
- "fmt"
- "reflect"
- )
- type Settings struct {
- Name string
- Retries int
- Verbose bool
- hidden int
- }
- func applyDefaults(ptr any) {
- v := reflect.ValueOf(ptr).Elem()
- for f, fv := range v.Fields() {
- if !fv.CanSet() || !fv.IsZero() {
- continue
- }
- switch fv.Kind() {
- case reflect.String:
- fv.SetString("default")
- fmt.Println("套用預設值:", f.Name)
- case reflect.Int:
- fv.SetInt(3)
- fmt.Println("套用預設值:", f.Name)
- }
- }
- }
- func main() {
- x := 10
- fmt.Println(reflect.ValueOf(x).CanSet())
- p := reflect.ValueOf(&x).Elem()
- fmt.Println(p.CanSet())
- p.Set(reflect.ValueOf(99))
- fmt.Println("x =", x)
- s := Settings{Retries: 5}
- applyDefaults(&s)
- fmt.Printf("%+v\n", s)
- }
輸出:
- false
- true
- x = 99
- 套用預設值: Name
- {Name:default Retries:5 Verbose:false hidden:0}
IsZero() 判斷值是否為該型別的零值;Retries 已經是 5,所以保留原值;Verbose 是 bool,範例沒有處理這個種類;hidden 未匯出,CanSet() 為 false。MethodByName 與 Call
Value.MethodByName(name) 依名稱取得方法(已綁定接收者),找不到時回傳無效的 Value。Call(args) 以 []Value 傳入參數呼叫函式,回傳 []Value。只能取得匯出的方法;指標接收者的方法要從指標的
Value 取得(觀念見 指標接收者)。注意:參數個數或型別不符時
Call 會 panic。簽名:
- func (v Value) MethodByName(name string) Value
- func (v Value) Call(in []Value) []Value
範例:
- package main
- import (
- "fmt"
- "reflect"
- )
- type Calculator struct{ Base int }
- func (c Calculator) Add(n int) int { return c.Base + n }
- func (c Calculator) Mul(n int) int { return c.Base * n }
- func (c *Calculator) Reset() { c.Base = 0 }
- func main() {
- c := Calculator{Base: 10}
- v := reflect.ValueOf(c)
- for _, name := range []string{"Add", "Mul", "Div"} {
- m := v.MethodByName(name)
- if !m.IsValid() {
- fmt.Println(name, "不存在")
- continue
- }
- out := m.Call([]reflect.Value{reflect.ValueOf(5)})
- fmt.Println(name, "=>", out[0].Int())
- }
- fmt.Println("值的方法數:", v.NumMethod())
- fmt.Println("指標的方法數:", reflect.ValueOf(&c).NumMethod())
- reflect.ValueOf(&c).MethodByName("Reset").Call(nil)
- fmt.Println("Reset 後 Base =", c.Base)
- }
輸出:
- Add => 15
- Mul => 50
- Div 不存在
- 值的方法數: 2
- 指標的方法數: 3
- Reset 後 Base = 0
DeepEqual
深度比較兩個值是否相等:會遞迴比較切片元素、映射內容、結構體欄位、指標指向的值。
== 不能比較切片與映射,測試中比對複雜結構時常用 DeepEqual。注意幾個容易踩到的規則:
- nil 切片與空切片(
[]int{})不相等 - 型別不同就不相等,即使數值一樣(
int(1)與int64(1)) - 只是比較切片時,
slices.Equal更快也更明確;映射用maps.Equal
簽名:
- func DeepEqual(x, y any) bool
範例:
- package main
- import (
- "fmt"
- "reflect"
- )
- type Order struct {
- ID int
- Items []string
- Meta map[string]int
- }
- func main() {
- a := Order{ID: 1, Items: []string{"pen"}, Meta: map[string]int{"qty": 2}}
- b := Order{ID: 1, Items: []string{"pen"}, Meta: map[string]int{"qty": 2}}
- fmt.Println(reflect.DeepEqual(a, b))
- b.Items = append(b.Items, "ink")
- fmt.Println(reflect.DeepEqual(a, b))
- var nilSlice []int
- fmt.Println(reflect.DeepEqual(nilSlice, []int{}))
- fmt.Println(reflect.DeepEqual(1, int64(1)))
- }
輸出:
- true
- false
- false
- false
New 與 MakeSlice
在執行期依
Type 建立新值:New(t):配置一個型別為 t 的零值,回傳指向它的指標Value(相當於new(T))MakeSlice(t, len, cap):建立切片(相當於make([]E, len, cap)),t必須是切片型別Append(s, x...):附加元素(相當於append)
解碼器(如 JSON)就是用這些函式,在不知道具體型別的情況下建立目標物件。
簽名:
- func New(typ Type) Value
- func MakeSlice(typ Type, len, cap int) Value
- func Append(s Value, x ...Value) Value
範例:
- package main
- import (
- "fmt"
- "reflect"
- )
- type Point struct{ X, Y int }
- func main() {
- pt := reflect.TypeFor[Point]()
- pv := reflect.New(pt)
- pv.Elem().Field(0).SetInt(3)
- pv.Elem().Field(1).SetInt(4)
- p := pv.Interface().(*Point)
- fmt.Printf("%T %+v\n", p, *p)
- st := reflect.SliceOf(pt)
- s := reflect.MakeSlice(st, 0, 2)
- s = reflect.Append(s, pv.Elem(), reflect.ValueOf(Point{X: 9}))
- fmt.Println(s.Type(), s.Len(), s.Interface())
- }
輸出:
- *main.Point {X:3 Y:4}
- []main.Point 2 [{3 4} {9 0}]
SliceOf(t) 由元素型別組出切片型別 []t;同類的還有 MapOf、PointerTo、ChanOf。重點整理
TypeOf/TypeFor取得型別,ValueOf取得值;處理邏輯通常依Kind分支- 取值與設定方法要跟種類相符,否則 panic;呼叫前先檢查
Kind、IsValid、CanSet、CanInterface - 要修改值必須從指標開始:
reflect.ValueOf(&x).Elem() - 結構體欄位與 tag:
NumField/Field/Tag.Get,Go 1.26 起可用Fields()迭代器 DeepEqual會區分 nil 切片與空切片、也會區分型別- 反射慢且失去型別檢查,能用泛型或介面就不要用反射