Get into the habit of writing together! This is the 8th day of my participation in the "Nuggets Daily New Plan · April Update Challenge", click to view the details of the event .
Scan
The conversion method can realize thestruct/struct数组/map/map数组
conversion of any parameter to, and automatically recognize and execute the conversion according to the conversion target parameters input by the developer.
method definition
// 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)
复制代码
Automatically recognize conversion Struct
structures
sample code
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)
}
复制代码
operation result
Automatically recognize transformation Struct
arrays
sample code
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)
}
复制代码
operation result
Automatically identify and convert Map
sample code
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)
}
复制代码
operation result
Automatically recognize transformation Map
arrays
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)
}
复制代码
operation result
Summarize
In the development process of our Go language, the conversion of json data and structure is often encountered.
GoFrame encapsulates the Scan
conversion method for us to realize the conversion of any parameter to struct/struct数组/map/map数组
, and automatically recognizes and executes the conversion according to the conversion target parameters input by the developer.
At last
Thank you for reading, and welcome everyone: like, favorite,coin(focus on)! ! !