前面关于复杂类型的转换功能如果大家觉得还不够的话,那么您可以了解下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/frame/g"
  4. "github.com/gogf/gf/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. "Name": "john",
  3. "Uid": 1
  4. }