前面关于复杂类型的转换功能如果大家觉得还不够的话,那么您可以了解下 Scan 转换方法,该方法可以实现对任意参数到 struct/struct数组/map/map数组 的转换,并且根据开发者输入的转换目标参数自动识别执行转换。

该方法定义如下:

  1. // Scan automatically calls MapToMap, MapToMaps, Struct or Structs function according to
  2. // the type of parameter `pointer` to implement the converting.
  3. // It calls function MapToMap if `pointer` is type of *map to do the converting.
  4. // It calls function MapToMaps if `pointer` is type of *[]map/*[]*map to do the converting.
  5. // It calls function Struct if `pointer` is type of *struct/**struct to do the converting.
  6. // It calls function Structs if `pointer` is type of *[]struct/*[]*struct to do the converting.
  7. func Scan(params interface{}, pointer interface{}, mapping ...map[string]string) (err error)

我们接下来看几个示例便可快速理解。

自动识别转换 Struct

  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.Map{
  12. "uid": 1,
  13. "name": "john",
  14. }
  15. var user *User
  16. if err := gconv.Scan(params, &user); err != nil {
  17. panic(err)
  18. }
  19. g.Dump(user)
  20. }

执行后,输出结果为:

  1. {
  2. Uid: 1,
  3. Name: "john",
  4. }

自动识别转换 Struct 数组

  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.Scan(params, &users); err != nil {
  23. panic(err)
  24. }
  25. g.Dump(users)
  26. }

执行后,终端输出:

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

自动识别转换Map

  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. var (
  8. user map[string]string
  9. params = g.Map{
  10. "uid": 1,
  11. "name": "john",
  12. }
  13. )
  14. if err := gconv.Scan(params, &user); err != nil {
  15. panic(err)
  16. }
  17. g.Dump(user)
  18. }

执行后,输出结果为:

  1. {
  2. "uid": "1",
  3. "name": "john",
  4. }

自动识别转换 Map 数组

  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. var (
  8. users []map[string]string
  9. params = g.Slice{
  10. g.Map{
  11. "uid": 1,
  12. "name": "john",
  13. },
  14. g.Map{
  15. "uid": 2,
  16. "name": "smith",
  17. },
  18. }
  19. )
  20. if err := gconv.Scan(params, &users); err != nil {
  21. panic(err)
  22. }
  23. g.Dump(users)
  24. }

执行后,输出结果为:

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