Created
August 7, 2018 05:43
-
-
Save nojima/6ffa4b523490bee29439f08f7398b9fc to your computer and use it in GitHub Desktop.
Go で構造体のフィールド一覧をリフレクションで取得する
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ 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