本文介绍了有没有更简洁的方法来格式化.expect()消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我目前必须使用它来格式化.expect()
消息:
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?
推荐答案
首先,您不需要写[..]
如果您真的想惊慌但又想格式化错误消息,我想我会使用 assert!()
:
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();
}
如果需要,您还可以使用 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");
}
此外,这两种方法都避免每次都构造错误String
,这与用format!()
调用expect()
不同.
Also, both these methods avoid the construction of the error String
every time, unlike calling expect()
with format!()
.
这篇关于有没有更简洁的方法来格式化.expect()消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!