對golang protobuf 的擴展字段賦值時候一直提示proto: bad extension value type golang
clkUrl:="z.cn"ui
proto.SetExtension(seatbid, rtb.E_Clkurl, clkUrl)url
查看源碼後發現,對擴展字段賦值的時候會對第二個參數進行反射獲取類型,判斷第三個參數的類型和第二個是否匹配 ,spa
func SetExtension(pb Message, extension *ExtensionDesc, value interface{}) error {
epb, ok := extendable(pb)
if !ok {
return errors.New("proto: not an extendable proto")
}
if err := checkExtensionTypes(epb, extension); err != nil {
return err
}
typ := reflect.TypeOf(extension.ExtensionType)
if typ != reflect.TypeOf(value) {
return errors.New("proto: bad extension value type")
}
// nil extension values need to be caught early, because the
// encoder can't distinguish an ErrNil due to a nil extension
// from an ErrNil due to a missing field. Extensions are
// always optional, so the encoder would just swallow the error
// and drop all the extensions from the encoded message.
if reflect.ValueOf(value).IsNil() {
return fmt.Errorf("proto: SetExtension called with nil value of type %T", value)
}
extmap := epb.extensionsWrite()
extmap[extension.Field] = Extension{desc: extension, value: value}
return nil
}
經過打印第二個參數的類型發現 第二個參數類型是*string , 個人第三個參數是sring,問題已經明瞭。code
閱讀源碼是解決問題的最好途徑。blog
修改後的代碼以下:源碼
proto.SetExtension(seatbid, rtb.E_Clkurl, &clkUrl)string