Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I tell the compiler that my function terminates the program like process::exit()?

I have the following function that includes some error recovery logic and the process::exit(0) in the end:

fn gracefully_shutdown() {
    // Do some logic for the recover
    process::exit(7);
}

I want to call that function in the error case but match complains about incompatible arms. But it does not complain when I write it explicitly into a match arm like the following:

fn handle_result(my_result: Result<i32, MyError>) -> i32 {
    match my_result {
        Ok(val) => val,
        //Err(_error) => { process::exit(0); } // Does not complain
        Err(_error) => {
            gracefully_shutdown();
        } // Does complain
    }
}

Is it really hard for the compiler to understand that gracefully_shutdown() contains process::exit(0) in itself?

I would expect that I could have written the code in this way:

fn handle_result(my_result: Result<i32, MyError>) -> i32 {
    match my_result {
        Ok(val) => val,
        Err(_error) => {
            gracefully_shutdown();
        }
    }
}

Any ideas to make this work?

Playground

like image 443
Akiner Alkan Avatar asked Feb 08 '19 12:02

Akiner Alkan


People also ask

What is the function of exit ()?

The exit() function is used to terminate a process or function calling immediately in the program. It means any open file or function belonging to the process is closed immediately as the exit() function occurred in the program.

How do you terminate a program in C++?

In C++, you can exit a program in these ways: Call the exit function. Call the abort function. Execute a return statement from main .

What does exit return in C?

Answer: exit() is a system call which terminates current process. exit() is not an instruction of C language. Whereas, return() is a C language instruction/statement and it returns from the current function (i.e. provides exit status to calling function and provides control back to the calling function).

What is the return type of exit function?

Return uses exit code which is int value, to return to the calling function. Using the return statement in the main function means exiting the program with a status code; for example, return 0 means returning status code 0 to the operating system.


1 Answers

Change the signature of gracefully_shutdown to

fn gracefully_shutdown() -> ! {
    process::exit(7);
}

This will tell the compiler that this function never returns! The ! is called the never type.

For more information see

  • Why does Rust have a "Never" primitive type?
like image 108
hellow Avatar answered Sep 23 '22 17:09

hellow