Golang Code Pieces

复制一个对象

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

import (
    "fmt"
    "reflect"
)

type Animal interface {
    say()
}

type Base struct {
    Id int
}

type Dog struct {
    *Base
    name string
}

type Cat struct {
    Base
    Name  string
    Color string
}

func (c *Cat) say() {
    fmt.Printf("Cat: my Name is %s[%s]\n", c.Name, c.Color);
}

func (d *Dog) say() {
    fmt.Printf("Dog: my Name is %s\n", d.name);
}

func getCopyObj(a Animal) interface{} {
    reflectVal := reflect.ValueOf(a)
    // Indirect获取引用指向对象的类型
    t := reflect.Indirect(reflectVal).Type()
    obj := reflect.New(t)

    dst, ok := obj.Interface().(Animal)

    if !ok {
        panic("controller is not ControllerInterface")
    }

    elemVal := reflect.ValueOf(a).Elem()
    elemType := reflect.TypeOf(a).Elem()
    execElem := reflect.ValueOf(dst).Elem()


    numOfFields := elemVal.NumField()
    for i := 0; i < numOfFields; i++ {
        fieldType := elemType.Field(i)
        elemField := execElem.FieldByName(fieldType.Name)
        if elemField.CanSet() {
            fieldVal := elemVal.Field(i)
            elemField.Set(fieldVal)
        }
    }

    return dst
}

func showCopy(src Animal) {
    fmt.Printf("src: %+v\n", src)
    dst := getCopyObj(src)
    fmt.Printf("dst: %+v\n", dst)
}

func main() {
    c := &Cat{
        Base: Base{
            Id: 100,
        },
        Name:  "Tom",
        Color: "Red",
    }
    showCopy(c)

    d := &Dog{
        Base: &Base{
            Id: 99,
        },
        name: "Tony",
    }
    showCopy(d)
}

Output:


image.png
上一篇 下一篇

猜你喜欢

热点阅读