前面关于复杂类型的转换功能如果大家觉得还不够的话,那么您可以了解下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)
我们接下来看几个示例便可快速理解。
package main
import (
"github.com/GOgf/gf/v2/frame/g"
"github.com/gogf/gf/v2/util/gconv"
)
func main() {
type User struct {
Uid int
Name string
}
params := g.Map{
"uid": 1,
"name": "john",
}
var user *User
if err := gconv.Scan(params, &user); err != nil {
panic(err)
}
g.Dump(user)
}
执行后,输出结果为:
{
"Name": "john",
"Uid": 1
}
package main
import (
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/util/gconv"
)
func main() {
type User struct {
Uid int
Name string
}
params := g.Slice{
g.Map{
"uid": 1,
"name": "john",
},
g.Map{
"uid": 2,
"name": "smith",
},
}
var users []*User
if err := gconv.Scan(params, &users); err != nil {
panic(err)
}
g.Dump(users)
}
执行后,终端输出:
[
{
"Uid": 1,
"Name": "john"
},
{
"Uid": 2,
"Name": "smith"
}
]
package main
import (
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/util/gconv"
)
func main() {
var (
user map[string]string
params = g.Map{
"uid": 1,
"name": "john",
}
)
if err := gconv.Scan(params, &user); err != nil {
panic(err)
}
g.Dump(user)
}
执行后,输出结果为:
{
"Uid": "1",
"Name": "john"
}
package main
import (
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/util/gconv"
)
func main() {
var (
users []map[string]string
params = g.Slice{
g.Map{
"uid": 1,
"name": "john",
},
g.Map{
"uid": 2,
"name": "smith",
},
}
)
if err := gconv.Scan(params, &users); err != nil {
panic(err)
}
g.Dump(users)
}
执行后,输出结果为:
[
{
"name": "john",
"uid": "1"
},
{
"name": "smith",
"uid": "2"
}
]
标题名称:创新互联GoFrame教程:GoFrame 类型转换-Scan转换
网站路径:http://www.mswzjz.cn/qtweb/news34/125184.html
攀枝花网站建设、攀枝花网站运维推广公司-贝锐智能,是专注品牌与效果的网络营销公司;服务项目有等
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 贝锐智能