Type switch failing?

blov · · 480 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<pre><code>// 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 &#34;0 errors&#34; (zero value for MultiError) fmt.Println(ok) // prints false switch v := err.(type) { case schema.MultiError: // do something default: // do something } } </code></pre> <p>Reflection shows that it&#39;s of type<code>schema.MultiError</code> but both the type switch and the type assertion are failing. It falls to the default case</p> <hr/>**评论:**<br/><br/>iygwaz: <pre><p>Additional information: in the function where the error is first encountered, the type switch goes through the correct case:</p> <pre><code>if err := schema.NewDecoder().Decode(dst, r.Form); err != nil { switch err.(type) { case schema.MultiError: // passes through here (correct) default: // } return err } </code></pre></pre>titpetric: <pre><p>Please put a working sample on the <a href="https://play.golang.org" rel="nofollow">go playground</a>, it will make it easier for us to inspect what you have outside of this function.</p> <p>Are you sure you&#39;re not using a pointer, and the case should be <code>case *schema.MultiError</code>?</p> <p>Edit: here&#39;s my version of a <a href="https://play.golang.org/p/kBmONKpHUc9" rel="nofollow">working playground</a>, so I&#39;m betting there&#39;s some pointer mixup from what I&#39;ve seen dealing with type switches.</p></pre>

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

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