3 ms·
A common pattern is something like: fn main() { if let Err(e) = real_main() { let status = status_from_error(e); // print the error
by tomjakubowski 8y ago
A common pattern is something like:
fn main() {
if let Err(e) = real_main() {
let status = status_from_error(e);
// print the error message, or whatever
std::process:exit(status);
}
}
fn real_main() -> Result<(), TopErrorType> {
// ...
}
And simply returning Result<_, SomethingConvertibleToTopErrorType> from functions called by real_main that might need to exit the program.
I believe that in a recent stable version of Rust, you can make this even simpler and have `main()` return a Result directly.
edit: not quite as simple as I described, but maybe more powerful because of the Termination trait: https://github.com/rust-lang/rfcs/blob/master/text/1937-ques-in-main.md https://github.com/rust-lang/rfcs/blob/master/text/1937-ques... see: https://github.com/rust-lang/rfcs/blob/master/text/1937-ques-in-main.md#how-we-teach-this https://github.com/rust-lang/rfcs/blob/master/text/1937-ques...
fn main() -> Result<(), io::Error> {
let mut stdin = io::stdin();
let mut raw_stdout = io::stdout();
let mut stdout = raw_stdout.lock();
for line in stdin.lock().lines() {
stdout.write(line?.trim().as_bytes())?;
stdout.write(b"\n")?;
}
stdout.flush()
}
- firebacon 8y agoYes, currently doing something similar to that, but I'd much rather have it as a first-citizen feature. Returning result directly from main sounds very interesting! I will have to look into that thx. EDIT: I assume you mean RFC1937? Looks like it isn't implemented yet, so we will probably have to at least another year before we can get it in stable rust. But yes - without having read the entire RFC - I think that was what I was looking for!
- steveklabnik 8y agoPart of it is implemented; see https://play.rust-lang.org/?gist=d442c47833587ddeff2158492b0a9ee7&version=stable&mode=debug https://play.rust-lang.org/?gist=d442c47833587ddeff2158492b0... The rest of it makes it even better; it's a bit limited in ways right now.
- firebacon 8y agoOh nice! Will start using that as soon as we get to 1.26 :) -- currently stuck on 1.24 (upgrading takes a bunch of work since we're building under openembedded/bitbake, so I wait until the new version hits the upstream layer)
- steveklabnik 8y agoGreat! :D