有没有更简洁的方式来格式化 .expect() 消息? [英] Is there a more concise way to format .expect() message?

查看:24
本文介绍了有没有更简洁的方式来格式化 .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")[..]);
}

有没有更简洁的方法?

推荐答案

首先你不需要写[..]

如果你真的想恐慌但又想格式化错误消息,我想我会使用 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 crate:


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() 消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆