前面关于复杂类型的转换功能如果大家觉得还不够的话,那么您可以了解下Scan转换方法,该方法可以实现对任意参数到struct/struct数组/map/map数组的转换,并且根据开发者输入的转换目标参数自动识别执行转换。
该方法定义如下:
// Scan automatically calls MapToMap, MapToMaps, Struct or Structs function according to// the type of parameter `pointer` to implement the converting.// It calls function MapToMap if `pointer` is type of *map to do the converting.// It calls function MapToMaps if `pointer` is type of *[]map/*[]*map to do the converting.// It calls function Struct if `pointer` is type of *struct/**struct to do the converting.// It calls function Structs if `pointer` is type of *[]struct/*[]*struct to do the converting.func Scan(params interface{}, pointer interface{}, mapping ...map[string]string) (err error)
自动识别转换Struct
package mainimport ("github.com/gogf/gf/frame/g""github.com/gogf/gf/util/gconv")func main() {type User struct {Uid intName string}params := g.Map{"uid": 1,"name": "john",}var user *Userif err := gconv.Scan(params, &user); err != nil {panic(err)}g.Dump(user)}
执行后,输出结果为:
{"Name": "john","Uid": 1}
