当前位置: > > > > go中将字符串映射到UUID
来源:stackoverflow
2024-04-25 22:45:26
0浏览
收藏
学习Golang要努力,但是不要急!今天的这篇文章《go中将字符串映射到UUID》将会介绍到等等知识点,如果你想深入学习Golang,可以关注我!我会持续更新相关文章的,希望对大家都能有所帮助!
问题内容
我正在使用 mitchellh/mapstruct 从 map[string]interface{}
映射到 struct
有没有办法告诉mapstruct
将string
转换为uuid.uuid
?
map[string]接口{}
:
{ "id": "af7926b1-98eb-4c96-a2ba-7e429085b2ad", "title": "new title", }
struct
package entities import ( "github.com/google/uuid" ) type Post struct { Id uuid.UUID `json:"id"` Title string `json:"title"` }
正确答案
您可以添加 decodehookfunc
:
func decode(input, output interface{}) error { config := &mapstructure.DecoderConfig{ DecodeHook: mapstructure.ComposeDecodeHookFunc( stringToUUIDHookFunc(), ), Result: &output, } decoder, err := mapstructure.NewDecoder(config) if err != nil { return err } return decoder.Decode(input) } func stringToUUIDHookFunc() mapstructure.DecodeHookFunc { return func(f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) { if f.Kind() != reflect.String { return data, nil } if t != reflect.TypeOf(uuid.UUID{}) { return data, nil } return uuid.Parse(data.(string)) } }
- 来源:
- 文档:
今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注公众号,一起学习编程~