LoginSignup
16

More than 5 years have passed since last update.

構造体の値を別の構造体の値へコピーする

Last updated at Posted at 2014-10-02

メモ。

type Src struct {
    Name    string
    Age     uint16
    Address string
}

type Dst struct {
    Name string
    Age  uint16
}

例えば上のような2つの構造体があったとして

s := &Src{"A", 12, "Japan"}
d := new(Dst)
copyStruct(s, d)

fmt.Println(*d) // {A, 12}

みたいに、必要なフィールドだけ移すためのcopyStruct()関数を考える。

func copyStruct(src interface{}, dst interface{}) error {
    fv := reflect.ValueOf(src)

    ft := fv.Type()
    if fv.Kind() == reflect.Ptr {
        ft = ft.Elem()
        fv = fv.Elem()
    }

    tv := reflect.ValueOf(dst)
    if tv.Kind() != reflect.Ptr {
        return fmt.Errorf("[Error] non-pointer: %v", dst)
    }

    num := ft.NumField()
    for i := 0; i < num; i++ {
        field := ft.Field(i)

        if !field.Anonymous {
            name := field.Name
            srcField := fv.FieldByName(name)
            dstField := tv.Elem().FieldByName(name)

            if srcField.IsValid() && dstField.IsValid() {
                if srcField.Type() == dstField.Type() {
                    dstField.Set(srcField)
                }
            }
        }
    }

    return nil
}

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16