Skip to content

Instantly share code, notes, and snippets.

@tosone
Last active July 21, 2019 13:09
Show Gist options
  • Save tosone/5da9dc8dfad830506dbc9e067cc438be to your computer and use it in GitHub Desktop.
Save tosone/5da9dc8dfad830506dbc9e067cc438be to your computer and use it in GitHub Desktop.
[Golang reflect struct] #Go
package main
import (
"fmt"
"reflect"
"time"
)
func main() {
type T struct {
A int
B string
}
t := T{23, "skidoo"}
s := reflect.ValueOf(&t).Elem()
typeOfT := s.Type()
for i := 0; i < s.NumField(); i++ {
f := s.Field(i)
fmt.Printf("%d: %s %s = %v\n", i, typeOfT.Field(i).Name, f.Type(), f.Interface())
}
{
fmt.Println(time.Now().Format(time.RFC3339))
t, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
fmt.Println(t.Hour())
}
}
package main
import (
"fmt"
"reflect"
)
// Name of the struct tag used in examples
const tagName = "validate"
type User struct {
Id int `validate:"-"`
Name string `validate:"presence,min=2,max=32"`
Email string `validate:"email,required"`
}
func main() {
user := User{
Id: 1,
Name: "John Doe",
Email: "john@example",
}
// TypeOf returns the reflection Type that represents the dynamic type of variable.
// If variable is a nil interface value, TypeOf returns nil.
t := reflect.TypeOf(user)
// Get the type and kind of our user variable
fmt.Println("Type:", t.Name())
fmt.Println("Kind:", t.Kind())
// Iterate over all available fields and read the tag value
for i := 0; i < t.NumField(); i++ {
// Get the field, returns https://golang.org/pkg/reflect/#StructField
field := t.Field(i)
// Get the field tag value
tag := field.Tag.Get(tagName)
fmt.Printf("%d. %v (%v), tag: '%v'\n", i+1, field.Name, field.Type.Name(), tag)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment