Goto in Rust. For tail call optimization

In this keynote presentation at Oracle Guy Steele proposes a novel use for "goto". Keynote with Guy Steele - YouTube (see slide 20, 17 minutes in)

Basically he suggests using "goto" in a very limited way enabling the programmer to indicate that he wants tail call recursion.

I guess the idea is to tell the compiler not to bother with all that subroutine call mechanism for the last call in a function, rather optimize it with just loop back to the beginning.

This stuck me as such an off the wall idea I could not resist mentioning here. I wondered if anyone in the Rust project had seen that or thought about such a thing. Or is it a useful idea at all?

Along the way Guy shows how tail call recursion would be a very nice thing, in Java at least.

I skimmed the video (so possibly missed important parts.) About 10min in is where relevance comes in.

For simple tail recursion you want the compiler to do so without "assembly" (giving explicit instructions.) It's on the compiler writers todo list.

The video seems to be promoting more advanced code and optimization. The problem is you make a language more complicated; adding new syntax all for a infrequently used feature.

It got me thinking you could do similar in Rust with continuation. (Note: missing Generic/Box/Lifetime real functionality.)

enum Cont {
    Continue(Fn() -> Cont),
    Result(bool),
}

trait S {
    fn contains(&self, x:u64) -> bool {
        let mut f = || self.contains_cont(x);
        loop {
            match f() {
                Cont::Continue(g) => f = g,
                Cont::Result(b) => break b,
            }
        }
    }

    fn contains_cont(&self, x:u64) -> Cont;
}
2 Likes

Some related (but old) RFCs:

1 Like

It's not obvious to me that a goto is better here than just using a loop.

Also, in rust you can just use a combinator for tail recursion:

(Though I do hope one day we get become for explicit tail calls.)

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.