有没有更简洁的方法来格式化 .expect() 消息?

bux*_*bux 17 format rust

我目前必须使用它来格式化.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)

格式化字符串的成本有点高。这将避免格式化字符串,除非确实需要它。

  • 只是来这里想说的是,截至 2022 年 9 月,`cargo Clippy --fix` 自动执行此精确转换:`option.expect(&amp;format!("ah: {}", "nuts"));` 变为:`option .unwrap_or_else(|| 恐慌!(“啊:{}”,“坚果”));` (6认同)

Sta*_*eur 7

首先你不需要写 [..]


如果您真的想恐慌但又想格式化错误消息,我想我会使用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!()。


Pet*_*all 6

为了避免在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)