-
-
Save cghiban/6f7b27ee20bf1c5d0d8f0ef65a18b9a8 to your computer and use it in GitHub Desktop.
Golang Reflection Example
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 Location struct { | |
Lat float64 `json:"lat"` | |
Lon float64 `json:"lon"` | |
} | |
type Foo struct { | |
FirstName string `json:"first_name"` | |
Age int `json:"age"` | |
Loc Location `json:"location"` | |
} | |
func analyze(o any) { | |
val := reflect.ValueOf(o).Elem() | |
for i := 0; i < val.NumField(); i++ { | |
valueField := val.Field(i) | |
kind := valueField.Kind() | |
type_ := valueField.Type() | |
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("json")) | |
fmt.Printf(" Kind: %s,\t Type: %s\n", kind, type_) | |
} | |
} | |
func main() { | |
f := &Foo{ | |
FirstName: "Drew", | |
Age: 30, | |
Loc: Location{Lat: 42.1, Lon: -37.2}, | |
} | |
analyze(f) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment