Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
0
Help us understand the problem. What is going on with this article?
@yookihiroo

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

More than 1 year has passed since last update.

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

/**
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
Help us understand the problem. What is going on with this article?
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
yookihiroo
元修理工のプログラマです。 ソフトをやりたくて転職したらゲームを作っていました。

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
0
Help us understand the problem. What is going on with this article?