繁体   English   中英

设置指针类型的结构字段

[英]Set struct field of pointer type

任务很简单。 我有 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"`
}

如您所见,有一个我想隐藏的Salt字段,更改JSON字段名称,并将所有字段设为可选。 目标方法应该像这样使用 Foo 填充 FooView:

func MirrorFoo(foo Foo) (*FooView, error) {
  return &FooView{
    FooId: &foo.FooId,
    Bar:   &foo.Bar,
    Baz:   foo.Baz,
  }, nil
}

现在,我想对 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
}

当 FooId 在两种类型中都是 uuid.UUID 时,这段代码工作正常,但是当源是 uuid.UUID 并且目标是 *uuid.UUID 时它会失败,现在不知道如何克服这个问题。

不知何故,我需要做 dstField.Set(reflect.ValueOf(&uuid.UUID{}...)) 的模拟,我尝试过的一切都不起作用。 有任何想法吗?

是的,Addr() 为我工作,但没有

reflect.Copy()

它用于 arrays。我使用 reflect.New() 和 Set() 当前值实例化了新值。 地址可用。 这完全是黑魔法。 谢谢大家。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM