我有一个类型的变量,interface{}
我想使用反射更改字段的值。我该怎么做?interface{}
由于其他要求,变量必须是类型。如果变量的类型不是interface{}
all works,否则代码抛出
reflect: call of reflect.Value.FieldByName on interface Value
我的代码
package main
import (
"fmt"
"reflect"
)
func main() {
a := struct {
Name string
}{}
// works
reflect.ValueOf(&a).Elem().FieldByName("Name").SetString("Hello")
fmt.Printf("%#v\n", a)
var b interface{}
b = struct {
Name string
}{}
// panics
reflect.ValueOf(&b).Elem().FieldByName("Name").SetString("Hello")
fmt.Printf("%#v\n", b)
}