Type switch failing?

blov · 2018-05-11 20:30:11 · 589 次点击    
这是一个分享于 2018-05-11 20:30:11 的资源,其中的信息可能已经有所发展或是发生改变。
// when passing in a schema.MultiError
func FormatErrForResp(err error) error {
  fmt.Println(reflect.TypeOf(err)) // prints schema.MultiError

  what, ok := err.(schema.MultiError)
  fmt.Println(what) // prints "0 errors" (zero value for MultiError)
  fmt.Println(ok) // prints false

  switch v := err.(type) {
  case schema.MultiError:
    // do something
  default:
    // do something
  }
}

Reflection shows that it's of typeschema.MultiError but both the type switch and the type assertion are failing. It falls to the default case


评论:

iygwaz:

Additional information: in the function where the error is first encountered, the type switch goes through the correct case:

if err := schema.NewDecoder().Decode(dst, r.Form); err != nil {
  switch err.(type) {
  case schema.MultiError:
    // passes through here (correct)
  default:
    //
  }
   return err
}
titpetric:

Please put a working sample on the go playground, it will make it easier for us to inspect what you have outside of this function.

Are you sure you're not using a pointer, and the case should be case *schema.MultiError?

Edit: here's my version of a working playground, so I'm betting there's some pointer mixup from what I've seen dealing with type switches.


入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

589 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传