GoFrame框架Scan类型转换实例

2022-11-13 09:11:08 框架 实例 转换

前言

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数组的转换,并且根据开发者输入的转换目标参数自动识别执行转换。

以上就是GoFrame框架Scan类型转换实例的详细内容,更多关于GoFrame框架Scan类型转的资料请关注其它相关文章!

相关文章