[英]Set struct field of pointer type
The task is pretty simple.任务很简单。 I have struct for model Foo, and one for it's representation:
我有 model Foo 的结构,还有一个代表它:
type Foo struct {
FooId string
Bar string
Baz *string
Salt int64
}
type FooView struct {
FooId *string `json: "foo_id"`
Bar *string `json: "bar"`
Baz *string `json: "baz"`
}
As you may see, there is Salt field which I want to hide, change JSON field names, and do all the fields optional.如您所见,有一个我想隐藏的Salt字段,更改JSON字段名称,并将所有字段设为可选。 The target method should fill FooView using Foo like this:
目标方法应该像这样使用 Foo 填充 FooView:
func MirrorFoo(foo Foo) (*FooView, error) {
return &FooView{
FooId: &foo.FooId,
Bar: &foo.Bar,
Baz: foo.Baz,
}, nil
}
And now, I want to do the same with Go reflect:现在,我想对 Go 做同样的事情:
func Mirror(src interface{}, dstType reflect.Type) (interface{}, error) {
zeroValue := reflect.Value{}
srcValue := reflect.ValueOf(src)
srcType := srcValue.Type()
dstValue := reflect.New(dstType)
dstValueElem := dstValue.Elem()
for i := 0; i < srcType.NumField(); i++ {
srcTypeField := srcType.Field(i)
srcValueField := srcValue.FieldByName(srcTypeField.Name)
dstField := dstValueElem.FieldByName(srcTypeField.Name)
// if current source field exists in destination type
if dstField != zeroValue {
srcValueField := srcValue.Field(i)
if dstField.Kind() == reflect.Ptr && srcValueField.Kind() != reflect.Ptr {
panic("???")
} else {
dstField.Set(srcValueField)
}
}
}
return dstValue.Interface(), nil
}
This code works fine when FooId is uuid.UUID in both types, but it fails when source is uuid.UUID and destination is *uuid.UUID, and now do not know how to overcome this.当 FooId 在两种类型中都是 uuid.UUID 时,这段代码工作正常,但是当源是 uuid.UUID 并且目标是 *uuid.UUID 时它会失败,现在不知道如何克服这个问题。
Somehow I need to do analog of dstField.Set(reflect.ValueOf(&uuid.UUID{}...)) bit everything I've tried does not works.不知何故,我需要做 dstField.Set(reflect.ValueOf(&uuid.UUID{}...)) 的模拟,我尝试过的一切都不起作用。 Any ideas?
有任何想法吗?
Yep, Addr() worked for me, but without是的,Addr() 为我工作,但没有
reflect.Copy()
It's for arrays. I've instantiated new value using reflect.New() and.Set() current value.它用于 arrays。我使用 reflect.New() 和 Set() 当前值实例化了新值。 Address became available.
地址可用。 It's completely black magic.
这完全是黑魔法。 Thanks for all.
谢谢大家。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.