Golang Code Pieces

通过tag从一个对象复制到另外一个对象

2019-06-23  本文已影响0人  yanjusong
package main

import (
    "fmt"
    "reflect"
)

type T struct {
    A int    `newT:"AA"`
    B string `newT:"BB"`
}

type newT struct {
    AA int
    BB string
}

func copyFromValue() {
    t := T{
        A: 123,
        B: "hello",
    }
    tt := reflect.TypeOf(t)
    tv := reflect.ValueOf(t)

    newT := &newT{}
    newTValue := reflect.ValueOf(newT)

    for i := 0; i < tt.NumField(); i++ {
        field := tt.Field(i)
        newTTag := field.Tag.Get("newT")
        tValue := tv.Field(i)
        newTValue.Elem().FieldByName(newTTag).Set(tValue)
    }

    fmt.Println(newT)
}

func copyFromPointer() {
    t := &T{
        A: 123,
        B: "hello",
    }

    // t是reference类型,所以需要Elem
    // Elem()注释如下:
    // Elem returns the value that the interface v contains
    // or that the pointer v points to.
    // It panics if v's Kind is not Interface or Ptr.
    // It returns the zero Value if v is nil.
    tt := reflect.TypeOf(t).Elem()
    tv := reflect.ValueOf(t).Elem()

    newT := &newT{}
    newTValue := reflect.ValueOf(newT)

    for i := 0; i < tt.NumField(); i++ {
        field := tt.Field(i)
        newTTag := field.Tag.Get("newT")
        tValue := tv.Field(i)
        newTValue.Elem().FieldByName(newTTag).Set(tValue)
    }

    fmt.Println(newT)
}

func main() {
    copyFromValue()
    copyFromPointer()
}

上一篇 下一篇

猜你喜欢

热点阅读