Introduction

The gstructs component is used to conveniently obtain information about structures.

This is a low-level component, rarely used in general business, but used in framework, basic library, and middleware writing.

Usage:

  1. import "github.com/gogf/gf/v2/os/gstructs"

API Documentation:

https://pkg.go.dev/github.com/gogf/gf/v2/os/gstructs

Common Methods

Fields

  • Description: Fields returns the fields of the Pointer attribute of the input parameter in in the form of a Field slice.

  • Format:

  1. Fields(in FieldsInput) ([]Field, error)
  • Example:
  1. func main() {
  2. type User struct {
  3. Id int
  4. Name string `params:"name"`
  5. Pass string `my-tag1:"pass1" my-tag2:"pass2" params:"pass"`
  6. }
  7. var user *User
  8. fields, _ := gstructs.Fields(gstructs.FieldsInput{
  9. Pointer: user,
  10. RecursiveOption: 0,
  11. })
  12. g.Dump(fields)
  13. }
  14. // Output:
  15. [
  16. {
  17. Value: "<int Value>",
  18. Field: {
  19. Name: "Id",
  20. PkgPath: "",
  21. Type: "int",
  22. Tag: "",
  23. Offset: 0,
  24. Index: [
  25. 0,
  26. ],
  27. Anonymous: false,
  28. },
  29. TagValue: "",
  30. },
  31. {
  32. Value: {},
  33. Field: {
  34. Name: "Name",
  35. PkgPath: "",
  36. Type: "string",
  37. Tag: "params:\"name\"",
  38. Offset: 8,
  39. Index: [
  40. 1,
  41. ],
  42. Anonymous: false,
  43. },
  44. TagValue: "",
  45. },
  46. {
  47. Value: {},
  48. Field: {
  49. Name: "Pass",
  50. PkgPath: "",
  51. Type: "string",
  52. Tag: "my-tag1:\"pass1\" my-tag2:\"pass2\" params:\"pass\"",
  53. Offset: 24,
  54. Index: [
  55. 2,
  56. ],
  57. Anonymous: false,
  58. },
  59. TagValue: "",
  60. },
  61. ]

TagMapName

  • Description: TagMapName retrieves tag from the parameter pointer and returns it in the form of map[string]string.

  • Note:

    • The type of parameter pointer should be struct/*struct.
    • Only exported fields (fields with an uppercase initial) will be returned.
  • Format:
  1. TagMapName(pointer interface{}, priority []string) (map[string]string, error)
  • Example:
  1. func main() {
  2. type User struct {
  3. Id int
  4. Name string `params:"name"`
  5. Pass string `my-tag1:"pass1" my-tag2:"pass2" params:"pass"`
  6. }
  7. var user User
  8. m, _ := gstructs.TagMapName(user, []string{"params"})
  9. g.Dump(m)
  10. }
  11. // Output:
  12. {
  13. "name": "Name",
  14. "pass": "Pass",
  15. }