簡體   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