• Ephera@lemmy.ml
    link
    fedilink
    English
    arrow-up
    1
    ·
    11 hours ago

    I’m not sure, what you mean by “Chekhov’s footgun”, but well, it isn’t a footgun, so you won’t accidentally return a wrong value from the function, if that’s what you’re thinking.

    It’s not a Rust invention, most functional programming languages have implicit returns, but basically think less of them as a function return and more just as the value that a scope evaluates to.

    So, here’s a simple example:

    let sum = {
        let x = 5 + 9;
        3 * x
    };
    

    Obviously, this is an extremely contrived example, but yeah, as you can see, it does not even have to involve a function. The implicit return makes it so that sum is set to the result from 3 * x.
    And the scope-braces are nice here, because you can do intermediate steps without having x in scope for the rest of your function.

    In practice, if you see scope-braces and the line at the end does not have a semicolon, then that’s the value that the whole scope evaluates to. Those scope-braces can also be the braces of a function, but then you need to annotate what the function is going to return, too, so it’s practically impossible to return a wrong value.

    Well, and I would actually argue that explicit returns are a footgun in comparison.
    Because someone might introduce clean-up code at the end of the function and not realize that an explicit return skips that clean-up code, somewhere further up in the function.
    The implicit return always has to be at the end of the scope, so it’s not possible to accidentally skip code.