【问题标题】:unwrap_err() function seems to be returning T rather than Eunwrap_err() 函数似乎返回 T 而不是 E
【发布时间】:2023-01-12 03:32:33
【问题描述】:

我正在尝试以这种方式处理来自 websocket 连接的可能错误:

        let connection: Result<Client<TlsStream<TcpStream>>,WebSocketError>
                = client_builder.unwrap().connect_secure(Some(tls_connector.unwrap()));

        if connection.is_err() {
                println!("Error: {}", connection.unwrap_err());
        }

我收到的错误如下:

error[E0277]: `websocket::sync::Client<native_tls::TlsStream<std::net::TcpStream>>` doesn't implement `Debug`
  --> src/main.rs:29:25
   |
29 |         println!("Error: {}", connection.as_ref().unwrap_err());    
   |                               ^^^^^^^^^^^^^^^^^^^ ---------- required by a bound introduced by this call
   |                               |
   |                               `websocket::sync::Client<native_tls::TlsStream<std::net::TcpStream>>` cannot be formatted using `{:?}` because it doesn't implement `Debug`
   |
   = help: the trait `Debug` is not implemented for `websocket::sync::Client<native_tls::TlsStream<std::net::TcpStream>>`
   = note: required for `&websocket::sync::Client<native_tls::TlsStream<std::net::TcpStream>>` to implement `Debug`
note: required by a bound in `Result::<T, E>::unwrap_err`

这对我来说很奇怪,因为 unwrap_err() 应该返回一个 WebSocketError 枚举而不是 websocket::sync::Client<native_tls::TlsStreamstd::net::TcpStream> 正确地没有调试实现

我尝试了不同的解包函数,但老实说,我需要 unwrap_err() 函数。

【问题讨论】:

  • 如果不需要,请不要unwrap。整个笨拙的.is_err()后跟.unwrap_err()组合可以用简单的if let代替。
  • 有道理谢谢。

标签: rust websocket unwrap


【解决方案1】:

unwrap_err 将在它的恐慌消息中打印 Ok 内的值,因此对于 T 仍然需要 Debug。 如果不满意可以用if let

if let Err(e) = connection {
    println!("Error: {}", e);
}

【讨论】:

    【解决方案2】:

    如果有问题的Result不是Err变体,unwrap_err将会恐慌。它会发出包含 Ok 值的消息,这要求 T 实现 Debug

    不要用is_err手动检查,你应该像这样使用if let

    if let Err(e) = connection.as_ref() {
        println!("Error: {}", e);
    }
    

    【讨论】:

      猜你喜欢
      • 2019-01-06
      • 2021-06-05
      • 2020-05-05
      • 1970-01-01
      • 1970-01-01
      • 2011-09-04
      • 2018-12-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多