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 main import ( "github.com/gogf/gf/frame/g" "github.com/gogf/gf/util/gconv" ) func main() { type User struct { Uid int Name string } params := g.Map{ "uid": 1, "name": "王中阳", } var user *User if err := gconv.Scan(params, &user); err != nil { panic(err) } g.Dump(user) }
运行结果
自动识别转换Struct
数组
示例代码
package main import ( "github.com/gogf/gf/frame/g" "github.com/gogf/gf/util/gconv" ) func main() { type User struct { Uid int Name string } params := g.Slice{ g.Map{ "uid": 1, "name": "优弧", }, g.Map{ "uid": 2, "name": "船长", }, } var users []*User if err := gconv.Scan(params, &users); err != nil { panic(err) } g.Dump(users) }
运行结果
自动识别转换Map
示例代码
package main import ( "github.com/gogf/gf/frame/g" "github.com/gogf/gf/util/gconv" ) func main() { var ( user map[string]string params = g.Map{ "uid": 1, "name": "王中阳", } ) if err := gconv.Scan(params, &user); err != nil { panic(err) } g.Dump(user) }
运行结果
自动识别转换Map
数组
package main import ( "github.com/gogf/gf/frame/g" "github.com/gogf/gf/util/gconv" ) func main() { var ( users []map[string]string params = g.Slice{ g.Map{ "uid": 1, "name": "优弧", }, g.Map{ "uid": 2, "name": "船长", }, } ) if err := gconv.Scan(params, &users); err != nil { panic(err) } g.Dump(users) } 复制代码
运行结果
总结
我们使用Go语言的开发过程中,json数据和结构体的转换是经常遇到的。
GoFrame为我们封装了Scan
转换方法可以实现对任意参数到struct/struct数组/map/map数组
的转换,并且根据开发者输入的转换目标参数自动识别执行转换。