Help us understand the problem. What is going on with this article?

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

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

/**
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)
}
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした