【问题标题】:TcpStream::connect - match arms have incompatible typeTcpStream::connect - 匹配武器具有不兼容的类型
【发布时间】:2023-02-06 02:28:38
【问题描述】:

我正在尝试用 Rust 编写基本的网络代码,但遇到了一个我不明白的错误。到目前为止,我一直在使用 match 语句对 Rust 中的所有内容进行错误检查,但是当我尝试对 TcpStream::connect() 进行错误检查时,出现意外错误:

我的代码:

use std::net::TcpStream;

fn main() {
    let mut server = match TcpStream::connect("127.0.0.1:23456"){
        Ok(x) => x,
        Err(x) => println!("Could not connect to server: {x}"),
    };
}

编译器错误:

error[E0308]: `match` arms have incompatible types
 --> src/main.rs:8:19
  |
6 |       let mut server = match TcpStream::connect("127.0.0.1:23456"){
  |  ______________________-
7 | |         Ok(x) => x,
  | |                  - this is found to be of type `TcpStream`
8 | |         Err(x) => println!("Could not connect to server: {x}"),
  | |                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 
                        expected struct `TcpStream`, found `()`
9 | |     };
  | |_____- `match` arms have incompatible types
  |

每次我使用 match 语句时,它允许我将 Result 类型解构为 OK 情况下的返回值(如上所述),或错误情况下的错误字符串。

TcpStream::connect() 返回一个 TcpStream 是这样的情况,但是为什么编译器坚持错误情况也需要返回一个 TcpStream?

【问题讨论】:

    标签: sockets networking rust match


    【解决方案1】:

    match 语句的值被分配给 server

    但是,match 语句的两个分支都返回不同的类型。

    • Ok(x) 返回x,其类型为TcpStream
    • Err(x)返回println!()的结果,它有返回值()

    TcpStream() 不兼容。

    想想匹配语句之后的代码。 server 变量应该是什么?当错误发生时,您不会停止执行,您只需println!() 并继续。所以某物必须写入server 变量。

    如果您使用 panic!() 而不是 println!(),这意味着打印并中止,那么它会编译,因为它知道 Err 案例之后不会继续:

    use std::net::TcpStream;
    
    fn main() {
        let mut server = match TcpStream::connect("127.0.0.1:23456") {
            Ok(x) => x,
            Err(x) => panic!("Could not connect to server: {x}"),
        };
    }
    
    thread 'main' panicked at 'Could not connect to server: Connection refused (os error 111)', src/main.rs:6:19
    

    也就是说,如果这是您想要的行为,则有一个简短的形式:

    use std::net::TcpStream;
    
    fn main() {
        let mut server = TcpStream::connect("127.0.0.1:23456").expect("Could not connect to server");
    }
    
    thread 'main' panicked at 'Could not connect to server: Os { code: 111, kind: ConnectionRefused, message: "Connection refused" }', src/main.rs:4:60
    

    【讨论】:

    • 这是完全正确的。在我的其他匹配语句中,我一直在调用 return 以在出现错误时退出。 Rust 编译器继续给我带来惊喜。
    猜你喜欢
    • 1970-01-01
    • 2017-08-27
    • 1970-01-01
    • 1970-01-01
    • 2012-06-26
    • 1970-01-01
    • 2021-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多