LoginSignup
20
16

More than 5 years have passed since last update.

構造体のフィールドを列挙する

Last updated at Posted at 2015-01-29
package main

import (
    "reflect"
    "strconv"
)

type Test struct {
    Field1 string
    Field2 string
    Field3 int
}

func main() {

    st := Test{"value1", "value2", 1234}

    v := reflect.Indirect(reflect.ValueOf(st))
    t := v.Type()

    for i := 0; i < t.NumField(); i++ {
        // フィールド名
        println("Field: " + t.Field(i).Name)

        // 値
        f := v.Field(i)
        i := f.Interface()
        if value, ok := i.(int); ok {
            println("Value: " + strconv.Itoa(value))
        } else {
            println("Value: " + f.String())
        }
    }
}

https://play.golang.org/p/krjCI9Zvhn

20
16
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
20
16