我目前必须使用它来格式化.expect()消息:
fn main() {
let x: Option<&str> = None;
x.expect(&format!("the world is ending: {}", "foo")[..]);
}
Run Code Online (Sandbox Code Playgroud)
有没有更简洁的方法?
cam*_*ous 17
我会做:
option.unwrap_or_else(|_| panic!("ah: {}", "nuts"))
Run Code Online (Sandbox Code Playgroud)
格式化字符串的成本有点高。这将避免格式化字符串,除非确实需要它。
首先你不需要写 [..]
如果您真的想恐慌但又想格式化错误消息,我想我会使用assert!():
fn main() {
let x: Option<&str> = None;
assert!(x.is_some(), "the world is ending: {}", "foo");
let _x = x.unwrap();
}
Run Code Online (Sandbox Code Playgroud)
如果你愿意,你也可以使用unwrap板条箱:
use unwrap::unwrap;
fn main() {
let x: Option<&str> = None;
let _x = unwrap!(x, "the world is ending: {}", "foo");
}
Run Code Online (Sandbox Code Playgroud)
此外,这两种方法避免错误的建设String每一次,不像打电话expect()用format!()。
为了避免在Stringan 的情况下格式化和分配 a 的不必要开销Ok,您可以将 the 转换Option为 aResult然后解包它:
fn main() {
let x: Option<&str> = None;
x.ok_or_else(|| format!("the world is ending: {}", "foo"))
.unwrap();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4329 次 |
| 最近记录: |