Skip to content

Instantly share code, notes, and snippets.

@lucasrpb
Last active November 22, 2016 21:43
Show Gist options
  • Save lucasrpb/ca669e095a6fe494f74d to your computer and use it in GitHub Desktop.
Save lucasrpb/ca669e095a6fe494f74d to your computer and use it in GitHub Desktop.
This gist shows how to reflect a struct in GoLang :)
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