Introduction

As previously mentioned, the Struct method can be used for the conversion of struct objects; similarly, the conversion of struct arrays is achieved using the Structs method. The Structs method is built upon the Struct method, and all conversion rules are the same as Struct, with additional support for struct array types. Before understanding the Structs method, it is recommended to first understand the introduction to the Struct method: Type Conversion - Struct

Method Definition

The Structs method is defined as follows:

  1. // Structs converts any slice to given struct slice.
  2. func Structs(params interface{}, pointer interface{}, mapping ...map[string]string) (err error)

Here, the type of pointer for the target conversion parameter needs to be *[]struct/*[]*struct.

Usage Example

Let’s look at a simple example to understand it.

  1. package main
  2. import (
  3. "github.com/gogf/gf/v2/frame/g"
  4. "github.com/gogf/gf/v2/util/gconv"
  5. )
  6. func main() {
  7. type User struct {
  8. Uid int
  9. Name string
  10. }
  11. params := g.Slice{
  12. g.Map{
  13. "uid": 1,
  14. "name": "john",
  15. },
  16. g.Map{
  17. "uid": 2,
  18. "name": "smith",
  19. },
  20. }
  21. var users []*User
  22. if err := gconv.Structs(params, &users); err != nil {
  23. panic(err)
  24. }
  25. g.Dump(users)
  26. }

After execution, the terminal output is:

  1. [
  2. {
  3. Uid: 1,
  4. Name: "john",
  5. },
  6. {
  7. Uid: 2,
  8. Name: "smith",
  9. },
  10. ]