Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a more concise way to format .expect() message?

Tags:

format

rust

I currently have to use this to format a .expect() message:

fn main() {
    let x: Option<&str> = None;
    x.expect(&format!("the world is ending: {}", "foo")[..]);
}

Is there a less verbose way?

like image 599
bux Avatar asked Apr 04 '19 10:04

bux


3 Answers

I would do:

option.unwrap_or_else(|| panic!("ah: {}", "nuts"))

Formatting a string is somewhat costly. This will avoid formatting the string unless it is really needed.

like image 65
cambunctious Avatar answered Nov 06 '22 01:11

cambunctious


First you don't need to write [..]


If you really want to panic but also want to format the error message, I think I would use assert!():

fn main() {
    let x: Option<&str> = None;
    assert!(x.is_some(), "the world is ending: {}", "foo");
    let _x = x.unwrap();
}

If you want you could also use the unwrap crate:

use unwrap::unwrap;

fn main() {
    let x: Option<&str> = None;
    let _x = unwrap!(x, "the world is ending: {}", "foo");
}

Also, both these methods avoid the construction of the error String every time, unlike calling expect() with format!().

like image 8
Stargateur Avatar answered Nov 06 '22 00:11

Stargateur


To avoid the unnecessary overhead of formatting and allocating a String in the case of an Ok, you can convert the Option to a Result and then unwrap it:

fn main() {
    let x: Option<&str> = None;
    x.ok_or_else(|| format!("the world is ending: {}", "foo"))
        .unwrap();
}
like image 6
Peter Hall Avatar answered Nov 05 '22 23:11

Peter Hall