<p>I know this might be a really noob question but I'm really curious.</p>
<pre><code>package main
import "fmt"
type SomeFunc func()
func (sf SomeFunc) Hello() {
fmt.Println("Hello from some func!")
}
func runSomeFunc(sf SomeFunc) {
sf.Hello()
}
type SomeString string
func (ss SomeString) Hello() {
fmt.Println("Hello from some string!")
}
func runSomeString(ss SomeString) {
ss.Hello()
}
func main() {
a := func() {}
runSomeFunc(a) //this works
// uncomment below and it won't work
// b := "foobar"
// runSomeString(b)
}
</code></pre>
<p>Is there something about the types of functions and strings (and what else?) that makes them different when being handled in function arguments?</p>
<p>To make it work, I need to do: <code>runSomeSting(SomeString(b))</code></p>
<p>But I don't need to do the same for the function like this: <code>runSomeFunc(SomeFunc(a))</code></p>
<p>Thanks!</p>
<hr/>**评论:**<br/><br/>djherbis: <pre><p>It's explained in the spec:</p>
<p><a href="https://golang.org/ref/spec#Assignability" rel="nofollow">https://golang.org/ref/spec#Assignability</a></p>
<p><a href="https://golang.org/ref/spec#Types" rel="nofollow">https://golang.org/ref/spec#Types</a></p>
<p><a href="https://golang.org/ref/spec#Predeclared_identifiers" rel="nofollow">https://golang.org/ref/spec#Predeclared_identifiers</a></p>
<p>func() {} is not a named type</p>
<p>string is.</p>
<p>"x's type V and T have identical underlying types and at least one of V or T is not a named type."</p></pre>majidfn: <pre><p>Hey, although I believe this is better suited for StackOverflow, but here is why your code is not working: </p>
<p>You are defining <code>b</code> as string and pass it to your function, while your function expects <code>SomeString</code>. Although <code>SomeString</code> is an alias to type <code>string</code> but they are not the same from compiler's perspective. Therefore gives you the error. </p>
<p>In the simplest form you can fix your code by defining <code>b</code> like below:</p>
<blockquote>
<p>var b SomeString = "foobar"</p>
</blockquote>
<p>This was you are explicitly defining your var of the type you want.</p>
<p>Hope it helps.</p></pre>eldosoa: <pre><p>Thanks for the reply! Sorry, will post it in SO next time.</p>
<p>My question is why doesn't this hold true for functions? I didn't need to do <code>var a SomeFunc = func () {}</code></p></pre>
[noob question] If I pass in a function as an argument, it does a type conversion. If I pass a string, it doesn't do a type conversion. Why doesn't this code work?
polaris · · 317 次点击这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
0 回复
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传