Why can't I define a recursive function as a variable? I seem to be able to define arbitrary functions except when they recurse.
This is legal:
func f(i int) int { if i == 0 { return 1 } return i * f(i-1) } func main() { fmt.Println(f(2)) }
This is illegal:
var f func(int) int = func(i int) int { if i == 0 { return 1 } return i * f(i-1) } func main() { fmt.Println(f(2)) }
This is legal and I'm guessing it is just because you can figure out f after initialization:
func main() { var f *func(int) int; t := func(i int) int { if i == 0 { return 1 } return i * (*f)(i-1) } f = &t fmt.Println((*f)(2)) }
So it looks like it comes down to function and variable declarations of a function type are treated differently though from the reading the documentation I wouldn't expect that to be the case. Did I miss the part of the documentation detailing this?
I would expect the illegal case to work just because it works in other languages. Like in JavaScript:
(function () { var f = function (i) { if (i == 0) { return 1; } return i * f(i - 1); }; console.log(f(2)); })();
The below code would be the preferred way of doing what you describe. Note that you do not have to create an additional variable, nor do you have a pointer to a function:
package main import "fmt" func main() { var f func(int) int f = func(i int) int { if i == 0 { return 1 } return i * f(i-1) } fmt.Println(f(2)) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With