import (
    "fmt"
    "reflect"
)


type Foo struct {
    FirstName string `tag_name:"tag 1"`
    LastName  string `tag_name:"tag 2"`
    Age       int    `tag_name:"tag 3"`
}

func (f *Foo) reflect() {
    val := reflect.ValueOf(f).Elem()

    for i := 0; i < val.NumField(); i++ {
        valueField := val.Field(i)
        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("tag_name"))                                                  
    }   
}

func main() {
    f := &Foo{
        FirstName: "Drew",
        LastName:  "Olson",
        Age:       30, 
    }   

    f.reflect()

    x := struct{Foo string; Bar int }{"foo", 2}

    v := reflect.ValueOf(x)

    values := make([]interface{}, v.NumField())

    for i := 0; i < v.NumField(); i++ {
        values[i] = v.Field(i).Interface()
    }

    fmt.Println(values)
}

  

相关文章:

  • 2021-07-20
  • 2022-12-23
  • 2021-05-24
  • 2021-09-04
  • 2021-09-11
  • 2021-11-06
  • 2021-10-31
猜你喜欢
  • 2021-10-26
  • 2022-01-16
  • 2022-12-23
  • 2022-03-04
  • 2021-05-20
  • 2022-12-23
相关资源
相似解决方案