小编Chr*_*ris的帖子

通过反射将接口的值设置为指向结构的指针类型的结构字段

我正在尝试设置 struct.field = &otherStruct。但是,我必须使用反射,而 otherStruct 的类型是 interface{}。

我得到的错误是:

reflect.Set: value of type main.StructB is not assignable to type *main.StructB
Run Code Online (Sandbox Code Playgroud)

结构是已知的。otherStruct 的(真实)类型未知,但可以保证赋值是安全的(结构类型相同)。

代码:

type StrucA struct {
    Field *StrucB
}

type StrucB struct {}

func main() {
    a := StrucA{}
    var b interface{} = StrucB{}
    //above is set

    // Target: Set a.Field = &b
    reflect.ValueOf(&a).Elem().FieldByName("Field").Set(reflect.ValueOf(b)) // reflect.Set: value of type main.StrucB is not assignable to type *main.StrucB
}
Run Code Online (Sandbox Code Playgroud)

游乐场:https : //play.golang.org/p/LR_RgfBzsxa

我已经测试了很多不同的东西,但我无法解决它。

reflection go

4
推荐指数
1
解决办法
2735
查看次数

标签 统计

go ×1

reflection ×1