Skip to content

Explicit tail calls are now available on Rust Nightly (become keyword)

old.reddit.com
14 pointsmanaskarekar2 comments
On HN

Comments

Link to actual GitHub PR since Reddit blocks some ASNs: https://github.com/rust-lang/rust/pull/144232

From documentation, and a test in the PR:

    When tail calling a function, instead of its stack frame being added to the
    stack, the stack frame of the caller is directly replaced with the callee's.
    This means that as long as a loop in a call graph only uses tail calls, the
    stack growth will be bounded.

    This is useful for writing functional-style code (since it prevent recursion
    from exhausting resources) or for code optimization (since a tail call
    *might* be cheaper than a normal call, tail calls can be used in a similar
    manner to computed goto).

    pub fn fibonacci(n: u64, a: u64, b: u64) -> u64 {
        match n {
            0 => a,
            1 => b,
            _ => become fibonacci(n - 1, b, a + b),
        }
    }
AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.