Created
September 13, 2019 06:11
-
-
Save cgiacomi/d2443a9b6850b5dcd4680b75ae0c07db to your computer and use it in GitHub Desktop.
Go reflection of struct
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" | |
"strconv" | |
) | |
type User struct { | |
Name string | |
Age int | |
Sexy *bool | |
} | |
func main() { | |
user := User{Name: "chris", Age: 46} | |
Serialize(user) | |
} | |
func Serialize(in interface{}) { | |
typeOfI := reflect.TypeOf(in) | |
valOfI := reflect.ValueOf(in) | |
numFields := typeOfI.NumField() | |
fmt.Println(typeOfI) | |
fmt.Println("has " + strconv.Itoa(numFields) + " fields:") | |
for i := 0; i < numFields; i++ { | |
field := typeOfI.Field(i) | |
fName := field.Name | |
//fType := field.Type.String() | |
fieldByValue := valOfI.Field(i) | |
fKind := field.Type.Kind() | |
isPointer := fKind == reflect.Ptr | |
fmt.Print(" " + fName + " (" + fKind.String() + ") is ptr: " + strconv.FormatBool(isPointer) + " -> val: ") | |
if fKind == reflect.String { | |
fmt.Print(fieldByValue.String()) | |
} | |
if fKind == reflect.Int { | |
fmt.Print(fieldByValue.Int()) | |
} | |
if fKind == reflect.Ptr { | |
if fieldByValue.IsNil() { | |
fmt.Print("nil") | |
} else { | |
fmt.Print(fieldByValue.Pointer()) | |
} | |
} | |
fmt.Println() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment