Created
May 10, 2022 05:18
-
-
Save justinyanme/6ba86ee278a2f9de2062c8f98b26b606 to your computer and use it in GitHub Desktop.
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" | |
"strings" | |
) | |
type TestData struct { | |
ID int `tag1:"Tag1" tag2:"Tag2"` | |
Title string | |
} | |
func main() { | |
aSlice := []int{1, 2, 3} | |
aStr := "Hello World!" | |
aStrPtr := &aStr | |
aTestData := TestData{ID: 1, Title: "Test"} | |
aTestDataPtr := &aTestData | |
aSliceType := reflect.TypeOf(aSlice) | |
aStrType := reflect.TypeOf(aStr) | |
aStrPtrType := reflect.TypeOf(aStrPtr) | |
aTestDataType := reflect.TypeOf(aTestData) | |
aTestDataPtrType := reflect.TypeOf(aTestDataPtr) | |
printReflect(aSliceType, 0) | |
printReflect(aStrType, 0) | |
printReflect(aStrPtrType, 0) | |
printReflect(aTestDataType, 0) | |
printReflect(aTestDataPtrType, 0) | |
} | |
func printReflect(t reflect.Type, depth int) { | |
fmt.Println(strings.Repeat("\t", depth), "Type: (", t.Name(), ") Kind: (", t.Kind(), ")") | |
switch t.Kind() { | |
case reflect.Struct: | |
for i := 0; i < t.NumField(); i++ { | |
field := t.Field(i) | |
fmt.Println(strings.Repeat("\t", depth+1), "Field: (", field.Name, ") Type: (", field.Type, ") Tag: (", field.Tag, ")") | |
if field.Tag != "" { | |
fmt.Println(strings.Repeat("\t", depth+2), "Tag is", field.Tag) | |
fmt.Println(strings.Repeat("\t", depth+2), "tag1 is", field.Tag.Get("tag1"), " tag2 is", field.Tag.Get("tag2")) | |
} | |
} | |
case reflect.Array, reflect.Slice, reflect.Chan, reflect.Map, reflect.Ptr: | |
fmt.Println(strings.Repeat("\t", depth+1), "Element type: (", t.Elem(), ")") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment