亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

go中將字符串映射到UUID

go中將字符串映射到UUID

Go
不負相思意 2022-11-08 14:51:56
我正在使用mitchellh/mapstructure映射從map[string]interface{}到struct有沒有辦法告訴mapstructure轉換string為uuid.UUID?map[string]interface{}:{    "id": "af7926b1-98eb-4c96-a2ba-7e429085b2ad",    "title": "new title",}structpackage entitiesimport (    "github.com/google/uuid")type Post struct {    Id      uuid.UUID  `json:"id"`    Title   string     `json:"title"`}
查看完整描述

1 回答

?
慕標5832272

TA貢獻1966條經驗 獲得超4個贊

您可以添加一個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))

    }

}


查看完整回答
反對 回復 2022-11-08
  • 1 回答
  • 0 關注
  • 134 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號