2 回答

TA貢獻1871條經驗 獲得超13個贊
問題是反射值不可設置。要解決此問題,請從指針創建反射值。
// SetStringField2 sets strings fields on the struct pointed to by ps.
func SetStringField2(ps interface{}) {
v := reflect.ValueOf(ps).Elem() // Elem() dereferences pointer
for i := 0; i < v.NumField(); i++ {
fv := v.Field(i)
switch fv.Kind() {
case reflect.String:
fv.SetString("fieldCleanString2 set name")
}
}
}
將指向值的指針傳遞給函數:
student := Student{
"alice",
12,
}
SetStringField2(&student)

TA貢獻1804條經驗 獲得超7個贊
解決方案一:
package service
import (
"fmt"
"reflect"
"testing"
)
func SetStringField2(obj interface{}) {
Values := reflect.ValueOf(obj).Elem()
count := reflect.Indirect(reflect.ValueOf(obj)).NumField()
for i := 0; i < count; i++ {
fieldValue := Values.Field(i)
switch fieldValue.Kind() {
case reflect.String:
fieldValue.SetString("fieldCleanString2 set name")
}
}
}
func TestSetValue(t *testing.T) {
type Student struct {
Name string
Age int
}
student := &Student{
"alice",
12,
}
SetStringField2(student)
fmt.Print(student.Name)
}
- 2 回答
- 0 關注
- 201 瀏覽
添加回答
舉報