【发布时间】: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