Last active
November 22, 2016 21:43
-
-
Save lucasrpb/ca669e095a6fe494f74d to your computer and use it in GitHub Desktop.
This gist shows how to reflect a struct in GoLang :)
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 Cep struct { | |
Number string | |
} | |
type Address struct { | |
Street string | |
Cep Cep | |
} | |
type User struct { | |
Username string | |
Age int | |
Address Address | |
} | |
func attributes(f interface{}) { | |
ifv := reflect.ValueOf(f) | |
ift := reflect.TypeOf(f) | |
//r := reflect.ValueOf(f) | |
for i := 0; i < ift.NumField(); i++ { | |
v := ifv.Field(i) | |
tf := ift.Field(i) | |
k := v.Kind(); switch k { | |
case reflect.Int: | |
fmt.Printf("%v %v %v", v, k, tf.Name) | |
case reflect.Float64: | |
fmt.Printf("%v %v %v", k, tf.Name) | |
case reflect.String: | |
fmt.Printf("%v %v %v", v, k, tf.Name) | |
case reflect.Struct: | |
{ | |
fmt.Println() | |
fmt.Println("Struct", k, tf.Name) | |
attributes(v.Interface()) | |
} | |
default: | |
fmt.Printf("I don't know, ask stackoverflow!") | |
} | |
fmt.Println() | |
} | |
} | |
func main(){ | |
user := User{Username:"lucasrpb", Age: 26, Address: Address{Street: "Av. Brasil", Cep: Cep{Number: "123"}}} | |
attributes(user) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment