用法

  1. type Box struct {
  2. Width int `info:"width" desc:"盒子宽度"`
  3. Height int `info:"height" desc:"盒子高度"`
  4. }

通过反射获取

  1. package main
  2. import (
  3. "fmt"
  4. "reflect"
  5. )
  6. type Box struct {
  7. Width int `info:"width" desc:"盒子宽度"`
  8. Height int `info:"height" desc:"盒子高度"`
  9. }
  10. // 遍历结构体字段
  11. func do(obj interface{}) {
  12. elem := reflect.TypeOf(obj).Elem()
  13. for i:=0;i<elem.NumField();i++{
  14. field := elem.Field(i)
  15. fmt.Printf("Field:%v Desc:%v\n",field.Tag.Get("info"),field.Tag.Get("desc"))
  16. }
  17. }
  18. func main() {
  19. box :=Box{
  20. Width: 10,
  21. Height: 20,
  22. }
  23. do(&box)
  24. }
  1. Field:width Desc:盒子宽度
  2. Field:height Desc:盒子高度