Created
August 10, 2017 07:40
-
-
Save Nydan/b2f6bc9b1f68df5f590f4d91c35a16db to your computer and use it in GitHub Desktop.
Using reflect to know struct Field Name, Field Value and Tag Value
This file contains 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 Person struct { | |
FirstName string `tag_name:"tag 1"` | |
LastName string `tag_name:"tag 2"` | |
Age int `tag_name:"tag 3"` | |
} | |
func (p *Person) reflect() { | |
val := reflect.ValueOf(p).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() { | |
p := &Person{ | |
FirstName: "Danny", | |
LastName: "Aguswahyudi", | |
Age: 24, | |
} | |
p.reflect() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment