Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it ok to return in main?

Tags:

rust

Since mains return type is an empty tuple (), is it considered a work-around to use return; in fn main() ? I'd like to end my program but don't want to panic! , I just want to calmly end. Is there a standard way to end main early? Or is this ok to do? I come from a C++ background where if you need to return early from a function which does not return any value, you probably shouldn't be using a void to begin with, so I'm wondering if this is the same case with no return type for main()?

fn main() {
    // ...

    // if no cline args display usage and end
    if matches.free.is_empty() {
        print_usage(&program, options);
        return;

    // program continues
}
like image 520
Syntactic Fructose Avatar asked Nov 27 '25 20:11

Syntactic Fructose


1 Answers

It's perfectly fine at the language level to return early like this. In this case, you might also like the std::process::exit function, which also allows setting the return code of the process.

like image 116
huon Avatar answered Dec 01 '25 07:12

huon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!