0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

共通のフィールド名がある構造体同士でのコピー

Last updated at Posted at 2020-02-19

共通のフィールド名があるが、同じでは無い構造体から構造体への、フィールド値のコピーサンプル

/**
reflectを使用して、同じ名前、同じ型のフィールドに値をコピーするサンプル
*/
package main

import (
	"fmt"
	"reflect"
)

// 型のエイリアスを使っている場合でも通る
type UID int64

type Test1 struct {
	Id          UID
	Name        string
	Age         int
	Affiliation string
}
type Test2 struct {
	Id      UID
	Name    string
	Age     int
	Company string
}

func main() {

	st1 := Test1{128, "Bob", 1234, "製造"}

	v1 := reflect.ValueOf(st1)
	t1 := v1.Type()

	st2 := Test2{}
	v2 := reflect.ValueOf(&st2)

	for i := 0; i < t1.NumField(); i++ {
		// フィールド名
		name := t1.Field(i).Name
		// 値
		field := v1.Field(i)
		value := field.Interface()

		v := v2.Elem().FieldByName(name)
		if v.IsValid() {
			fmt.Printf("name=%s, type=%s, value=%#v\n", name, v.Type(), value)
			// コピー元と先の型が違うと、ここで落ちる
			v.Set(field)
		} else {
			// コピー先に同じ名前のフィールドが無かったので取得出来なかった場合
			fmt.Printf("no field[name=%s] found.\n", name)
		}
	}
	fmt.Printf("st2=%+v\n", st2)
}
0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?