Skip to content

Instantly share code, notes, and snippets.

@bokwoon95
Created November 14, 2020 05:17
Show Gist options
  • Save bokwoon95/11654c2bd9f38dca508c59d96b1a9f79 to your computer and use it in GitHub Desktop.
Save bokwoon95/11654c2bd9f38dca508c59d96b1a9f79 to your computer and use it in GitHub Desktop.
Golang Reflect Struct Example https://play.golang.org/p/duT92qd3_ot
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