[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 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>I know this might be a really noob question but I&#39;m really curious.</p> <pre><code>package main import &#34;fmt&#34; type SomeFunc func() func (sf SomeFunc) Hello() { fmt.Println(&#34;Hello from some func!&#34;) } func runSomeFunc(sf SomeFunc) { sf.Hello() } type SomeString string func (ss SomeString) Hello() { fmt.Println(&#34;Hello from some string!&#34;) } func runSomeString(ss SomeString) { ss.Hello() } func main() { a := func() {} runSomeFunc(a) //this works // uncomment below and it won&#39;t work // b := &#34;foobar&#34; // 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&#39;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&#39;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>&#34;x&#39;s type V and T have identical underlying types and at least one of V or T is not a named type.&#34;</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&#39;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 = &#34;foobar&#34;</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&#39;t this hold true for functions? I didn&#39;t need to do <code>var a SomeFunc = func () {}</code></p></pre>

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

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