Confusion on this example for error in go by example article

xuanbao · · 451 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>In the last example of this <a href="https://gobyexample.com/errors" rel="nofollow">blog</a></p> <pre><code> _, e := f2(42) if ae, ok := e.(*argError); ok { fmt.Println(ae.arg) fmt.Println(ae.prob) } </code></pre> <p>The author mention that <code>e.(*argError)</code> is a type assertion, but I couldn&#39;t reproduce it with other types.</p> <p>For <a href="https://play.golang.org/p/RyMbh1Bic0" rel="nofollow">example</a> </p> <pre><code>var a int = 2 fmt.Println(a.(int)) </code></pre> <p>will run into error</p> <p>invalid type assertion: a.(int) (non-interface type int on left)</p> <p>even though the variable is an int</p> <p>So my question is, what are the rules of type assertion?</p> <hr/>**评论:**<br/><br/>Midnightblues: <pre><p>You can only assert the type of an interface to a concrete type or other interface. You can&#39;t assert the type of a variable with a concrete type because it&#39;s already known for certain. </p></pre>adonovan76: <pre><p>Not so. Type assertions to interface types are legal and useful. For example, <code>io.WriteString</code> uses a type assertion to detect whether an <code>io.Writer</code> also has a <code>WriteString</code> method and, if so, calls it in preference to <code>Write</code>: <a href="https://golang.org/src/io/io.go?s=10020:10075#L277" rel="nofollow">https://golang.org/src/io/io.go?s=10020:10075#L277</a></p></pre>Midnightblues: <pre><p>You&#39;re right, my mistake. Just meant you can&#39;t type assert a concrete type. Thanks for the example :)</p></pre>danhardman: <pre><p>The alternative is of course, type conversion (AKA casting). Where you can wrap values in a type to convert them to that type, like so:</p> <pre><code>var i int = 42 var f float64 = float64(i) var u uint = uint(f) </code></pre> <p>Source: <a href="https://tour.golang.org/basics/13" rel="nofollow">A tour of Go: Type conversions</a></p></pre>seriouslulz: <pre><p>It fails because the type of a isn&#39;t an interface type: <a href="https://golang.org/ref/spec#Type_assertions" rel="nofollow">https://golang.org/ref/spec#Type_assertions</a></p></pre>earthboundkid: <pre><p>Change it to <code>var a interface{} = 1</code> and it will work. </p></pre>

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

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