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 关注
- 133 浏览
添加回答
举报