Skip to content

Instantly share code, notes, and snippets.

@nojima
Created August 7, 2018 05:43
Show Gist options
  • Save nojima/6ffa4b523490bee29439f08f7398b9fc to your computer and use it in GitHub Desktop.
Save nojima/6ffa4b523490bee29439f08f7398b9fc to your computer and use it in GitHub Desktop.
Go で構造体のフィールド一覧をリフレクションで取得する
package main
import (
"reflect"
"fmt"
)
type Hoge struct {
Hello string
World string
Number int
_ABC string
privateMember string
}
func main() {
hoge := Hoge{
Hello: "hello",
World: "world",
Number: 30,
_ABC: "_abc",
privateMember: "private",
}
hogeValue := reflect.ValueOf(hoge)
hogeType := reflect.TypeOf(hoge)
numField := hogeValue.NumField()
for i := 0; i < numField; i++ {
field := hogeType.Field(i)
fieldValue := hogeValue.Field(i).String()
fmt.Printf("%s = %s\n", field.Name, fieldValue)
}
}
$ go run main.go
Hello = hello
World = world
Number = <int Value>
_ABC = _abc
privateMember = private
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment