以下是一些使用 gconv.structs 的示例代码,展示了如何在 GoFrame 框架中进行结构体转换:
示例1:基本使用
package main
import (
"fmt"
"github.com/gogf/gf/frame/g"
"github.com/gogf/gf/util/gconv"
)
type User struct {
Uid int
Name string
SiteUrl string
NickName string
Pass1 string `gconv:"password1"`
Pass2 string `gconv:"password2"`
}
func main() {
// 使用默认映射规则绑定属性值到对象
user := new(User)
params1 := g.Map{
"uid": 1,
"Name": "john",
"siteurl": "https://goframe.org",
"nick_name": "johng",
"PASS1": "123",
"PASS2": "456",
}
if err := gconv.Struct(params1, user); err == nil {
g.Dump(user)
}
// 使用struct tag映射绑定属性值到对象
user = new(User)
params2 := g.Map{
"uid": 2,
"name": "smith",
"site-url": "https://goframe.org",
"nick name": "johng",
"password1": "111",
"password2": "222",
}
if err := gconv.Struct(params2, user); err == nil {
g.Dump(user)
}
}
示例2:复杂类型转换
1. struct属性为struct或*struct
package main
import (
"fmt"
"github.com/gogf/gf/util/gconv"
"github.com/gogf/gf/frame/g"
)
type Score struct {
Name string
Result int
}
type User1 struct {
Scores Score
}
type User2 struct {
Scores *Score
}
func main() {
user1 := new(User1)
user2 := new(User2)
scores := g.Map{
"Scores": g.Map{
"Name": "john",
"Result": 100,
},
}
if err := gconv.Struct(scores, user1); err != nil {
fmt.Println(err)
} else {
g.Dump(user1)
}
if err := gconv.Struct(scores, user2); err != nil {
fmt.Println(err)
} else {
g.Dump(user2)
}
}
2. struct属性为slice,数值为slice
package main
import (
"fmt"
"github.com/gogf/gf/util/gconv"
"github.com/gogf/gf/frame/g"
)
type Score struct {
Name string
Result int
}
type User struct {
Scores []Score
}
func main() {
user := new(User)
scores := g.Map{
"Scores": g.Slice{
g.Map{
"Name": "john",
"Result": 100,
},
g.Map{
"Name": "smith",
"Result": 60,
},
},
}
// 嵌套struct转换,属性为slice类型,数值为slice map类型
if err := gconv.Struct(scores, user); err != nil {
fmt.Println(err)
} else {
g.Dump(user)
}
}
这些示例展示了如何使用 gconv.structs 进行基本的和复杂的结构体转换,包括使用默认映射规则、struct tag映射以及处理嵌套结构体和切片。