<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))("astring")
</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 "fmt"
func main() {
var fn = func(a string) {
fmt.Println(a)
}
var v interface{} = fn
var fn2 func(string)
fn2 = v.(func(string))
fn2("astring")
}
</code></pre>
<p>If you just tried to do</p>
<pre><code>fn2 = v
</code></pre>
<p>we'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't really a func(string), then this'll panic at runtime.</p>
<p>(I'm just elaborating on what schoenobates said, in case it'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's a type assertion. It'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
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传