<p>Just start to learn golang. I apologise if this has been asked before.</p>
<p>I want to define a function that recursively calls itself, <em>inside</em> a function, e.g. a fibonacci function inside another function.</p>
<pre><code>func bar() {
func fib(n int) int {
if n < 2 {
return n
}
return fib(n-1) + fib(n-2)
}
r := fib(10)
// some further work
}
</code></pre>
<p>Of course, the above code has compile error.</p>
<p>Any way I can do this? (Without lifting <code>fib()</code> to top level outside <code>bar()</code>.) Or golang just forbids this style?</p>
<hr/>**评论:**<br/><br/>gargamelus: <pre><pre><code>func bar() {
var fib func(n int) int
fib = func(n int) int {
if n < 2 {
return n
}
return fib(n-1) + fib(n-2)
}
r := fib(10)
fmt.Println(r)
}
</code></pre></pre>jeffrallen: <pre><p>Explanation: This is a rare case in Go where something like a C prototype is needed. At the time you call fib inside the function you are defining, the compiler does not yet know what its signature is. By making the fib variable first, and letting it start with a zero value, when you come back to set it later the thing you set it to (the anonymous function) can refer to it, since it already has a type set.</p>
<p>-jeff</p></pre>justinisrael: <pre><p>One way to solve this is to create "fib" as a variable pointing to a function:</p>
<p><a href="https://play.golang.org/p/HX-dIcPBs7" rel="nofollow">https://play.golang.org/p/HX-dIcPBs7</a></p>
<p>That way the reference to fib exists at the correct scope.</p></pre>flyee: <pre><p>thank you and @gargamelus </p>
<p>this is exactly what i am looking for.</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
0 回复
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传