Rust:使 unwrap() 打印 error.display() 而不是 error.debug()

Dal*_*rio 3 debugging error-handling rust unwrap display

在 Rust 程序中,我使用 a Result,它使用 aString作为其Error类型:

fn foo() -> Result<String, String>

我作为错误返回的字符串看起来像这样:
lorem\nipsum

现在我调用我的函数并将其解包如下:
foo.unwrap();

现在,当foo()返回 an时Error,它会打印错误,如下所示:
lorem\nipsum

然而,我实际上想看到的是以下错误消息:

lorem
ipsum
Run Code Online (Sandbox Code Playgroud)

据我所知,这种行为的原因是unwrap(),在字符串的情况下,调用debug()而不是display()which 的实现方式不同(新行显示为新行,但调试打印为“\n”) 。

有没有一种快速的方法可以让我以一种调用的方式 unwrap() 我的结果,而display()不是debug()让打印的错误实际显示换行符而不是“\n”?

isa*_*tfa 8

unwrap不应该显示漂亮的错误消息。当unwrap恐慌时,就应该有什么事情出了严重的问题。如果你想打印出String里面的内容,Err你可以将其打印到stderrwith eprintln!,然后正确处理错误:

if let Err(e) = foo() {
    eprintln!("{}", e);
    // handle the error properly here
}
Run Code Online (Sandbox Code Playgroud)

  • IOW:失败的“unwrap()”是程序中的一个错误。 (3认同)