透過反射修改值
最後更新
本頁說明反射的「可設定性(settability)」規則,以及如何用
Elem 與 Set 系列方法修改變數、結構體欄位、切片與映射。為什麼不能直接改
reflect.ValueOf(x) 收到的是 x 的副本。就像影印一份文件,在影本上塗改不會改到正本,Go 乾脆禁止你改影本,免得以為改到了卻沒有效果。要修改原本的變數,必須傳入它的指標,再透過指標找到原本那塊記憶體。可以修改的
Value 需要同時滿足兩個條件:| 條件 | 說明 |
|---|---|
| 可定址(addressable) | 這個值代表一塊實際存在的變數記憶體,而不是副本 |
| 不是經由未匯出欄位取得 | 反射不能繞過套件封裝去改小寫欄位 |
CanSet() 一次檢查這兩件事。CanSet:可設定性
對不可設定的
Value 呼叫 SetInt 等方法會 panic。修改前先用 CanSet() 檢查,是撰寫反射程式的基本習慣。簽名:
- func (v Value) CanSet() bool
範例:
- package main
- import (
- "fmt"
- "reflect"
- )
- func main() {
- x := 10
- v := reflect.ValueOf(x)
- fmt.Println("CanSet:", v.CanSet())
- defer func() {
- fmt.Println("recover:", recover())
- }()
- v.SetInt(20)
- }
輸出:
- CanSet: false
- recover: reflect: reflect.Value.SetInt using unaddressable value
錯誤訊息裡的 unaddressable 就是「不可定址」:
v 只是 x 的副本。Elem:透過指標找到原值
把
&x 傳給 ValueOf,得到的是「指標」這個 Value,指標本身同樣是副本,不能設定。呼叫 Elem() 才會走到指標指向的那塊記憶體,也就是 x 本身,這時 CanSet() 為 true。簽名:
- func (v Value) Elem() Value
範例:
- package main
- import (
- "fmt"
- "reflect"
- )
- func main() {
- x := 10
- p := reflect.ValueOf(&x)
- fmt.Println("p Kind:", p.Kind(), "CanSet:", p.CanSet())
- e := p.Elem()
- fmt.Println("e Kind:", e.Kind(), "CanSet:", e.CanSet())
- e.SetInt(99)
- fmt.Println("x =", x)
- }
輸出:
- p Kind: ptr CanSet: false
- e Kind: int CanSet: true
- x = 99
注意:
Elem() 只能用在 Kind 為 Pointer 或 Interface 的 Value,其他 Kind 會 panic;nil 指標呼叫 Elem() 會得到零值 Value(IsValid() 為 false)。Set 系列方法
| 方法 | 適用 Kind |
|---|---|
SetInt(int64) | 各種有號整數 |
SetUint(uint64) | 各種無號整數 |
SetFloat(float64) | float32、float64 |
SetString(string) | string |
SetBool(bool) | bool |
Set(Value) | 任何型別,但新值必須可指派給目標型別 |
簽名:
- func (v Value) Set(x Value)
- func (v Value) SetInt(x int64)
- func (v Value) SetString(x string)
範例:
- package main
- import (
- "fmt"
- "reflect"
- )
- func main() {
- var (
- n int
- name string
- ok bool
- tags []string
- )
- reflect.ValueOf(&n).Elem().SetInt(42)
- reflect.ValueOf(&name).Elem().SetString("gopher")
- reflect.ValueOf(&ok).Elem().SetBool(true)
- reflect.ValueOf(&tags).Elem().Set(reflect.ValueOf([]string{"a", "b"}))
- fmt.Println(n, name, ok, tags)
- defer func() {
- fmt.Println("recover:", recover())
- }()
- reflect.ValueOf(&n).Elem().Set(reflect.ValueOf("not int"))
- }
輸出:
- 42 gopher true [a b]
- recover: reflect.Set: value of type string is not assignable to type int
注意:型別不相容時
Set 會 panic,而不是回傳錯誤。這類錯誤編譯器抓不到,只會在執行期出現。修改結構體欄位
實務上最常見的用途:依名稱設定結構體欄位,例如把設定檔的字串值填進 Config 結構體。流程是:
- 確認收到的是「結構體指標」,再用
Elem()取得結構體本身 FieldByName找欄位,IsValid()為false表示欄位不存在CanSet()為false表示是未匯出欄位- 依欄位 Kind 把字串轉型後呼叫對應的
Set方法
範例:
- package main
- import (
- "fmt"
- "reflect"
- "strconv"
- )
- type Settings struct {
- Host string
- Port int
- Verbose bool
- token string
- }
- func apply(dst any, values map[string]string) error {
- v := reflect.ValueOf(dst)
- if v.Kind() != reflect.Pointer || v.Elem().Kind() != reflect.Struct {
- return fmt.Errorf("[Invalid] apply: 需要結構體指標,收到 %s", v.Type())
- }
- v = v.Elem()
- for key, raw := range values {
- f := v.FieldByName(key)
- if !f.IsValid() {
- return fmt.Errorf("[Not found] apply: 欄位 %q", key)
- }
- if !f.CanSet() {
- return fmt.Errorf("[Denied] apply: 欄位 %q 未匯出,無法設定", key)
- }
- switch f.Kind() {
- case reflect.String:
- f.SetString(raw)
- case reflect.Int:
- n, err := strconv.Atoi(raw)
- if err != nil {
- return fmt.Errorf("[Invalid] apply: 欄位 %q 的值 %q 不是整數", key, raw)
- }
- f.SetInt(int64(n))
- case reflect.Bool:
- b, err := strconv.ParseBool(raw)
- if err != nil {
- return fmt.Errorf("[Invalid] apply: 欄位 %q 的值 %q 不是布林", key, raw)
- }
- f.SetBool(b)
- }
- }
- return nil
- }
- func main() {
- var s Settings
- err := apply(&s, map[string]string{"Host": "example.com", "Port": "8080", "Verbose": "true"})
- fmt.Printf("%+v %v\n", s, err)
- fmt.Println(apply(&s, map[string]string{"token": "abc"}))
- fmt.Println(apply(&s, map[string]string{"Timeout": "3"}))
- fmt.Println(apply(s, map[string]string{"Host": "x"}))
- }
輸出:
- {Host:example.com Port:8080 Verbose:true token:} <nil>
- [Denied] apply: 欄位 "token" 未匯出,無法設定
- [Not found] apply: 欄位 "Timeout"
- [Invalid] apply: 需要結構體指標,收到 main.Settings
傳入
s 而不是 &s 時,函式回傳錯誤而不是 panic,因為一開始就檢查了 Kind。修改切片、陣列與映射
不同容器的可設定性不一樣:
| 容器 | 元素是否可設定 | 原因 |
|---|---|---|
| 切片 | 可以 | 切片內部指向一塊共用的底層陣列,Index(i) 就是那塊記憶體 |
| 陣列 | 經由指標 Elem() 才可以 | 陣列是值型別,ValueOf(arr) 拿到的是整個副本 |
| 映射 | 不用 Set,改用 SetMapIndex | 映射元素不可定址;傳入零值 Value 代表刪除該鍵 |
簽名:
- func (v Value) Index(i int) Value
- func (v Value) SetMapIndex(key, elem Value)
範例:
- package main
- import (
- "fmt"
- "reflect"
- )
- func main() {
- nums := []int{1, 2, 3}
- sv := reflect.ValueOf(nums)
- fmt.Println("slice elem CanSet:", sv.Index(0).CanSet())
- sv.Index(0).SetInt(100)
- fmt.Println(nums)
- arr := [2]int{1, 2}
- fmt.Println("array elem CanSet:", reflect.ValueOf(arr).Index(0).CanSet())
- reflect.ValueOf(&arr).Elem().Index(0).SetInt(7)
- fmt.Println(arr)
- m := map[string]int{"a": 1}
- mv := reflect.ValueOf(m)
- mv.SetMapIndex(reflect.ValueOf("b"), reflect.ValueOf(2))
- mv.SetMapIndex(reflect.ValueOf("a"), reflect.Value{})
- fmt.Println(m)
- }
輸出:
- slice elem CanSet: true
- [100 2 3]
- array elem CanSet: false
- [7 2]
- map[b:2]
重點整理
ValueOf(x)拿到的是副本,不能修改;要改原值就傳指標再呼叫Elem()- 修改前用
CanSet()檢查:需要可定址,且不是經由未匯出欄位取得 SetInt、SetString、Set型別不符時會 panic,編譯期抓不到- 切片元素可直接設定;陣列要經由指標;映射用
SetMapIndex,傳零值Value表示刪除 - 撰寫通用函式時先檢查 Kind 並回傳錯誤,別讓呼叫端遇到 panic