Created
November 14, 2020 05:17
-
-
Save bokwoon95/11654c2bd9f38dca508c59d96b1a9f79 to your computer and use it in GitHub Desktop.
Golang Reflect Struct Example https://play.golang.org/p/duT92qd3_ot
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 { | |
User string `tag_name:"tag 1"` | |
Fruit string `tag_name:"tag 2"` | |
Score int `tag_name:"tag 3"` | |
} | |
func PrintStruct(x interface{}) { | |
structValue := reflect.ValueOf(x) | |
structType := structValue.Type() | |
for i := 0; i < structValue.NumField(); i++ { | |
structField := structType.Field(i) | |
Name := structField.Name | |
Value := structValue.Field(i).Interface() | |
Type := reflect.ValueOf(Value).Type() | |
TagName := structField.Tag.Get("tag_name") | |
fmt.Printf("Name: %s,\t Value: %v,\t Type: %s,\t TagName: %s\n", Name, Value, Type, TagName) | |
} | |
} | |
func main() { | |
foo := Foo{ | |
User: "Bob", | |
Fruit: "banana", | |
Score: 300, | |
} | |
PrintStruct(foo) | |
// Name: User, Value: Bob, Type: string, TagName: tag 1 | |
// Name: Fruit, Value: banana, Type: string, TagName: tag 2 | |
// Name: Score, Value: 300, Type: int, TagName: tag 3 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment