What is the usage of this and what is it called?

xuanbao · · 591 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>So I was browsing Go questions on SO, and came across <a href="http://stackoverflow.com/a/6770333/2255715">this</a> answer.</p> <p>The part in question is this:</p> <pre><code>v.(func(string))(&#34;astring&#34;) </code></pre> <p>What is the reason for doing <em>.()</em> on a variable? What is it named?</p> <hr/>**评论:**<br/><br/>schoenobates: <pre><p>Its a type assertion that the type of v is a function that accepts a single string.</p> <p><a href="https://play.golang.org/p/YUXrlLpjwC">https://play.golang.org/p/YUXrlLpjwC</a></p> <p><a href="https://golang.org/ref/spec#Type_assertions">https://golang.org/ref/spec#Type_assertions</a></p></pre>dilap: <pre><p>Yup; maybe a little clearer if you separate the type assertion from the function call:</p> <pre><code>package main import &#34;fmt&#34; func main() { var fn = func(a string) { fmt.Println(a) } var v interface{} = fn var fn2 func(string) fn2 = v.(func(string)) fn2(&#34;astring&#34;) } </code></pre> <p>If you just tried to do</p> <pre><code>fn2 = v </code></pre> <p>we&#39;d get a type error from the compiler, so we have to do a type assertion:</p> <pre><code>fn2 = v.(func(string)) </code></pre> <p>Note that if v isn&#39;t really a func(string), then this&#39;ll panic at runtime.</p> <p>(I&#39;m just elaborating on what schoenobates said, in case it&#39;s helpful to anyone.)</p></pre>f2f: <pre><blockquote> <p>fn2 = v.(func(string))</p> </blockquote> <p>note that a type assertion also allows you to check if the assertion is successful:</p> <pre><code>if fn2, ok := v.(func(string)); ok { ... } </code></pre></pre>dfcarvalho: <pre><p>I believe that&#39;s a type assertion. It&#39;s like type casting but for interfaces (where the casting might fail/not be compatible)</p> <p>Edit: <a href="https://golang.org/doc/effective_go.html#interface_conversions">https://golang.org/doc/effective_go.html#interface_conversions</a></p></pre>

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

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