TheCloudlessSky
TheCloudlessSky

Reputation: 18353

Why do return expressions use semicolons when they're unnecessary?

I'm learning Rust and I've found something confusing with functions. According to the official reference, a return expression:

.. [is] denoted with the keyword return. Evaluating a return expression moves its argument into the output slot of the current function, destroys the current function activation frame, and transfers control to the caller frame.

So, this program works:

fn main() {
    let current_hour = 10;
    let message = get_message(current_hour);

    println!("Good {0}", message);
}

fn get_message(current_hour: i32) -> &'static str {

    if current_hour < 11 {
        return "Morning"
    }
    else if current_hour < 17 {
        return "Afternoon"
    }
    else {
        return "Evening"
    }

}

And when I add semi-colons to the "return" expressions, it still works:

fn main() {
    let current_hour = 10;
    let message = get_message(current_hour);

    println!("Good {0}", message);
}

fn get_message(current_hour: i32) -> &'static str {

    if current_hour < 11 {
        return "Morning";
    }
    else if current_hour < 17 {
        return "Afternoon";
    }
    else {
        return "Evening";
    }

}

My understanding of expression statements (e.g. expr;) is that it will evaluate the expr expression, and ignore the result (instead it will use ()). In the case of using return expr;, there doesn't seem to be a reason for using ; since return expr destroys the current function activation frame (and would then ignore the ;).

So, why does a lot of Rust code that I've seen use the semi-colon if it's not necessary (and in fact makes learning about Rust's functions very confusing... since it feels like it's contradictory). Is it just an idiom from other languages that has carried over?

Upvotes: 7

Views: 2294

Answers (1)

huon
huon

Reputation: 102066

Is it just an idiom from other languages that has carried over?

Yes, I think that's it, just habit and possibly a general sense of aesthetics about what feels weird and what doesn't (which is of course influenced by someone's previous languages).

AFAICT, the only difference it can make is for something like

fn foo() {
    return;
    println!("hi");
}

where return needs to be a statement... but the code after the return is unreachable (which the compiler will tell you), so this likely doesn't occur that much in real code.

Upvotes: 6

Related Questions