2 回答
TA贡献1796条经验 获得超10个赞
问题是反射值不可设置。要解决此问题,请从指针创建反射值。
// 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贡献1859条经验 获得超6个赞
解决方案1:
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 关注
- 158 浏览
添加回答
举报