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

时间:2019-04-04 10:04:37

标签: rust

我目前必须使用它来格式化.expect()消息:

fn main() {
    let x: Option<&str> = None;
    x.expect(&format!("the world is ending: {}", "foo")[..]);
}

有没有那么冗长的方式?

3 个答案:

答案 0 :(得分:5)

我会做的:

option.unwrap_or_else(|| panic!("ah: {}", "nuts"))

格式化字符串有些昂贵。除非确实需要,否则这将避免格式化字符串。

答案 1 :(得分:1)

为避免在String情况下格式化Ok和分配Option的不必要开销,可以将Result转换为fn main() { let x: Option<&str> = None; x.ok_or_else(|| format!("the world is ending: {}", "foo")) .unwrap(); } 然后解开包装:

Sub posneg()

    Dim cell As Range
    Dim pn As Range

    Set pn = rawday.Range(rawday.Range("A4"). _
    Offset(0, 42), rawday.Range("A4").Offset(0, 42).End(xlUp))

    For Each cell In pn
        If cell = "Incomplete" Then cell = ""

        ElseIf cell = "Yes" Then
            cell.Offset(0, -30) = Abs(cell.Offset(0, -30)) * -1
            cell.Offset(0, -30).Value = Abs(cell.Offset(0, -30)) * -1
        ElseIf cell = "No" Then
            cell.Offset(0, -30) = Abs(cell.Offset(0, -30)) * 1
            cell.Offset(0, -30).Value = Abs(cell.Offset(0, -30)) * 1
        End If       
    Next

End Sub

答案 2 :(得分:0)

首先,您不需要写[..]


如果您真的想惊慌又想格式化错误消息,我想我会使用assert!()

fn main() {
    let x: Option<&str> = None;

    assert!(x.is_some(), "the world is ending: {}", "foo");
    let _x = x.unwrap();
}

如果您愿意,也可以使用unwrap条板箱:

use unwrap::unwrap;

fn main() {
    let x: Option<&str> = None;

    let _x = unwrap!(x, "the world is ending: {}", "foo");
}

此外,这两种方法都避免了每次String每次调用expect()时都构造错误format!()