GoFrame 類型轉(zhuǎn)換-Scan轉(zhuǎn)換

2022-03-30 15:48 更新

前面關(guān)于復(fù)雜類型的轉(zhuǎn)換功能如果大家覺(jué)得還不夠的話,那么您可以了解下?Scan?轉(zhuǎn)換方法,該方法可以實(shí)現(xiàn)對(duì)任意參數(shù)到?struct/struct?數(shù)組?/map/map?數(shù)組的轉(zhuǎn)換,并且根據(jù)開(kāi)發(fā)者輸入的轉(zhuǎn)換目標(biāo)參數(shù)自動(dòng)識(shí)別執(zhí)行轉(zhuǎn)換。

該方法定義如下:

// 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)

我們接下來(lái)看幾個(gè)示例便可快速理解。

自動(dòng)識(shí)別轉(zhuǎn)換Struct

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)
}

執(zhí)行后,輸出結(jié)果為:

{
	"Name": "john",
	"Uid": 1
}

自動(dòng)識(shí)別轉(zhuǎn)換Struct數(shù)組

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)
}

執(zhí)行后,終端輸出:

[
    {
            "Uid": 1,
            "Name": "john"
    },
    {
            "Uid": 2,
            "Name": "smith"
    }
]

自動(dòng)識(shí)別轉(zhuǎn)換Map

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)
}

執(zhí)行后,輸出結(jié)果為:

{
   "Uid": "1", 
   "Name": "john"
}

自動(dòng)識(shí)別轉(zhuǎn)換Map數(shù)組

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)
}

執(zhí)行后,輸出結(jié)果為:

[
    {
            "name": "john",
            "uid": "1"
    },
    {
            "name": "smith",
            "uid": "2"
    }
]


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)