“预期类型‘()’"是什么意思?是指匹配表达式吗?

“预期类型‘()’

问题描述:

我正在重写一个简单的基于 TCP 的服务器来试验 Rust.它应该检索客户端的输入,然后匹配该输入以运行函数:

I'm rewriting a simple TCP based server to experiment with Rust. It should retrieve input of an client and then match that input to run a function:

use std::io::BufRead;
use std::io::BufReader;
use std::io::BufWriter;
use std::io::Write;
use std::net::{TcpListener, TcpStream};
use std::thread;

fn handle_connection(stream: TcpStream) {
    let stream_clone = stream.try_clone().unwrap();
    let mut reader = BufReader::new(stream);
    let mut writer = BufWriter::new(stream_clone);
    loop {
        let mut s = String::new();
        reader.read_line(&mut s).unwrap();

        match s.as_str() {
            //"test" => writer.write(s.as_bytes()).unwrap();
            "test" => writer.write(b"test successfull").unwrap(),
            _ => writer.write(b"Command not recognized...").unwrap(),
        }

        writer.flush().unwrap();
    }
}

fn main() {
    let listener = TcpListener::bind("127.0.0.1:8888").unwrap();
    for stream in listener.incoming() {
        thread::spawn(move || {
            handle_connection(stream.unwrap());
        });
    }
}

和错误:

error[E0308]: mismatched types
  --> src/main.rs:16:9
   |
16 | /         match s.as_str() {
17 | |             //"test" => writer.write(s.as_bytes()).unwrap();
18 | |             "test" => writer.write(b"test successfull").unwrap(),
19 | |             _ => writer.write(b"Command not recognized...").unwrap(),
20 | |         }
   | |_________^ expected (), found usize
   |
   = note: expected type `()`
              found type `usize`

我现在的主要问题是检查检索到的字节是否属于匹配项,但我不太确定如何实现.

My main problem now is to check the retrieved bytes if they belong to an match and I'm not quite sure how to achieve that.

我在网上找不到解决方法,rustc --explain 也没有帮助我

I couldn't find a fix for this online, rustc --explain didn't help me either

match 表达式后添加分号.

Add a semicolon after your match expression.

所有match臂的类型都是usize,所以match的结果类型也是usize代码>.您的代码有效

The type of all of the match arms is usize, so the resulting type of the match is also a usize. Your code is effectively

fn main() {
    {
        42
    }

    println!("Hi");
}

error[E0308]: mismatched types
 --> src/main.rs:3:9
  |
3 |         42
  |         ^^ expected `()`, found integer

另见: