我正试图用Rust编写基本的网络代码,但遇到了一个我不理解的错误.到目前为止,我一直使用Match语句来错误判断Rust中的所有内容,但是当我try 错误判断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语句,它就允许我将结果类型分解为OK情况下的返回值(如上所述),或错误情况下的错误字符串.
TcpStream::Connect()确实返回TcpStream,但是为什么编译器坚持错误情况也需要返回TcpStream呢?