-
-
Save KevinHeaton-Money4nothin/d4947f183c7a63a66049642571a6170b to your computer and use it in GitHub Desktop.
Golang Reflection Example
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
| <script src="https://gist.github.com/KevinHeaton-Money4nothin/d4947f183c7a63a66049642571a6170b.js"></script> |
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 ( | |
| "fmt" | |
| "reflect" | |
| ) | |
| type Foo struct { | |
| FirstName string `tag_name:"tag 1"` | |
| LastName string `tag_name:"tag 2"` | |
| Age int `tag_name:"tag 3"` | |
| } | |
| func (f *Foo) reflect() { | |
| val := reflect.ValueOf(f).Elem() | |
| for i := 0; i < val.NumField(); i++ { | |
| valueField := val.Field(i) | |
| typeField := val.Type().Field(i) | |
| tag := typeField.Tag | |
| fmt.Printf("Field Name: %s,\t Field Value: %v,\t Tag Value: %s\n", typeField.Name, valueField.Interface(), tag.Get("tag_name")) | |
| } | |
| } | |
| func main() { | |
| f := &Foo{ | |
| FirstName: "Drew", | |
| LastName: "Olson", | |
| Age: 30, | |
| } | |
| f.reflect() | |
| } |
Author
KevinHeaton-Money4nothin
commented
Sep 22, 2016
<script src="https://gist.github.com/KevinHeaton-Money4nothin/d4947f183c7a63a66049642571a6170b.js"></script>
Author
<script src="https://gist.github.com/KevinHeaton-Money4nothin/d4947f183c7a63a66049642571a6170b.js"></script>
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment