1 Star 0 Fork 2

XXFork/utils

forked from aesoper/utils 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
map.go 1.13 KB
一键复制 编辑 原始数据 按行查看 历史
aesoper 提交于 2020-08-26 14:14 +08:00 . “删除日志”
/**
* @Author: aesoper
* @Description:
* @File: map
* @Version: 1.0.0
* @Date: 2020/5/19 21:11
*/
package utils
import (
"github.com/mitchellh/mapstructure"
"reflect"
)
// 泛类型map转换struct
func WeakMap2Struct(input interface{}, output interface{}, tags ...string) error {
tag := ""
if len(tags) >= 1 {
tag = tags[0]
}
decoder, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
TagName: tag,
Result: output,
WeaklyTypedInput: true,
})
if err != nil {
return err
}
return decoder.Decode(input)
}
// 强类型map转换struct
func Map2Struct(input interface{}, output interface{}, tags ...string) error {
tag := ""
if len(tags) >= 1 {
tag = tags[0]
}
decoder, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
TagName: tag,
Result: output,
})
if err != nil {
return err
}
return decoder.Decode(input)
}
func Struct2Map(input interface{}) map[string]interface{} {
t := reflect.TypeOf(input)
v := reflect.ValueOf(input)
var data = make(map[string]interface{})
for i := 0; i < t.NumField(); i++ {
data[t.Field(i).Name] = v.Field(i).Interface()
}
return data
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/XXFork/utils.git
[email protected]:XXFork/utils.git
XXFork
utils
utils
master

搜索帮助