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

喜欢而已 提交于 2020-12-12 02:09:47

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/27876561/why-do-return-expressions-use-semicolons-when-theyre-unnecessary

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!