In Rust the main function is defined like this:
fn main() { }
This function does not allow for a return value though. Why would a language not allow for a return value and is there a way to return something anyway? Would I be able to safely use the C exit(int)
function, or will this cause leaks and whatnot?
The return keyword can be used to return a value inside a function's body. When this keyword isn't used, the last expression is implicitly considered to be the return value. If a function returns a value, its return type is specified in the signature using -> after the parentheses () .
Rust doesn't have "implicit returns" because (almost) everything in Rust is an expression which has a return value. The exception to this are statements of which there are only a few. One statement is ; , which takes an expression, throws away the expression's value, and evaluate to () instead.
By default, rustc produces a binary crate, not a library one, which needs a main() .
As of Rust 1.26, main
can return a Result
:
use std::fs::File; fn main() -> Result<(), std::io::Error> { let f = File::open("bar.txt")?; Ok(()) }
The returned error code in this case is 1 in case of an error. With File::open("bar.txt").expect("file not found");
instead, an error value of 101 is returned (at least on my machine).
Also, if you want to return a more generic error, use:
use std::error::Error; ... fn main() -> Result<(), Box<dyn Error>> { ... }
std::process::exit(code: i32)
is the way to exit with a code.
Rust does it this way so that there is a consistent explicit interface for returning a value from a program, wherever it is set from. If main
starts a series of tasks then any of these can set the return value, even if main
has exited.
Rust does have a way to write a main
function that returns a value, however it is normally abstracted within stdlib. See the documentation on writing an executable without stdlib for details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With