snippetrustMinor
Is there a more concise way to format .expect() message?
Viewed 0 times
conciseexpectmessagetherewayformatmore
Problem
I currently have to use this to format a
Is there a less verbose way?
.expect() message:fn main() {
let x: Option = None;
x.expect(&format!("the world is ending: {}", "foo")[..]);
}
Is there a less verbose way?
Solution
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
If you want you could also use the
Also, both these methods avoid the construction of the error
[..]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 = 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 = 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!().Context
Stack Overflow Q#55513198, score: 13
Revisions (0)
No revisions yet.