Map转换

    转换方法:

    1. package main
    2. import (
    3. "fmt"
    4. "github.com/gogf/gf/util/gconv"
    5. )
    6. func main() {
    7. type User struct {
    8. Uid int `c:"uid"`
    9. }
    10. // 对象
    11. fmt.Println(gconv.Map(User{
    12. Uid : 1,
    13. Name : "john",
    14. }))
    15. // 对象指针
    16. fmt.Println(gconv.Map(&User{
    17. Uid : 1,
    18. Name : "john",
    19. }))
    20. fmt.Println(gconv.Map(map[int]int{
    21. 100 : 10000,
    22. }))
    23. }

    执行后,输出结果如下:

    1. map[uid:1 name:john]
    2. map[uid:1 name:john]
    3. map[100:10000]

    执行后,输出结果为:

    1. map[Uid:100 password1:123 password2:456]
    1. package main
    2. import (
    3. "github.com/gogf/gf/frame/g"
    4. "github.com/gogf/gf/util/gconv"
    5. )
    6. func main() {
    7. type User struct {
    8. Id int `c:"uid"`
    9. Name string `my-tag:"nick-name" c:"name"`
    10. }
    11. user := &User{
    12. Id: 1,
    13. }
    14. g.Dump(gconv.Map(user, "my-tag"))
    15. }

    当参数为map/struct/*struct类型时,如果键值/属性为一个对象(或者对象指针)时,Map方法将会将对象转换为结果的一个键值。我们可以使用MapDeep方法递归转换参数的子对象。

    使用示例:

    1. package main
    2. import (
    3. "fmt"
    4. "github.com/gogf/gf/util/gconv"
    5. )
    6. func main() {
    7. type Base struct {
    8. Id int `c:"id"`
    9. CreateTime string `c:"create_time"`
    10. }
    11. type User struct {
    12. Base `c:"base"`
    13. Passport string `c:"passport"`
    14. Password string `c:"password"`
    15. Nickname string `c:"nickname"`
    16. }
    17. user := new(User)
    18. user.Id = 1
    19. user.Nickname = "John"
    20. user.Passport = "johng"
    21. user.Password = "123456"
    22. user.CreateTime = "2019"
    23. fmt.Println(gconv.Map(user))
    24. fmt.Println(gconv.MapDeep(user))
    25. }
    1. map[create_time:2019 id:1 nickname:John passport:johng password:123456]