20

How to recurse a closure in Go?

Suppose I have a closure like

recur := func(){
    recur()
}

Compiler says:

undefined: recur

How can i implement it? Why is it happening?

Ezequiel Moreno
  • 2,228
  • 22
  • 27

1 Answers1

25

it happens because of how the order of evaluation works.

As of December 2015 (go.1.5.1), there isn't any language feature providing it.

Possible workarounds:

var recur func()
recur = func(){
    recur()
}

//or

type recurF func(recurF)

recur := func(recur recurF) {
    recur(recur)
}

More Info: https://github.com/golang/go/issues/226

Ezequiel Moreno
  • 2,228
  • 22
  • 27