dxuhuang
dxuhuang

Reputation: 1082

Tail Call Optimization in Go

Does the Go programming language, as of now, optimize tail calls? If not, does it at least optimize tail-recursive calls of a function to itself?

Upvotes: 56

Views: 19034

Answers (4)

ZAN DoYe
ZAN DoYe

Reputation: 59

I just wrote a new library to deal with this restriction. Thanks to the new generics language feature comes with Go 1.18. Now, type safe stackless mutually recursive functions are possible.

https://github.com/kandu/go_tailcall

Upvotes: 5

user12817546
user12817546

Reputation:

Extending @Rostyslav's excellent answer. If you must have a tail call, (in this example a tail recursive call) you can do something like this.

package main

import "fmt"

func tail(i int) {
    if i == 0 {
        return
    } else {
        fmt.Println(i)
        tail(i - 1) //tail recursive call
    }
}
func main() {
    tail(3) //3, 2, 1
}

Upvotes: 5

Rostyslav Dzinko
Rostyslav Dzinko

Reputation: 40825

Everything you can find over the Internet, that "Go supports tailable recursions in some cases", and that was told in mailing list:

It is already there in 6g/8g for certain cases, and in gccgo somewhat more generally.

We do not currently plan to change the language to require that compilers implement tail call optimization in all cases. If you must have a tail call, you use a loop or a goto statement.

To get those cases you'd better dig into golang source, which is open.

Upvotes: 20

Jeremy Wall
Jeremy Wall

Reputation: 25265

It does not. Nor is there any plan to according to the core development team on the mailing list.

Upvotes: 3

Related Questions