匹配表达式上的“预期类型`()`”是什么意思?

时间:2019-06-03 14:32:26

标签: rust

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

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`

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

我在网上找不到此修复程序,rustc --explain也没有帮助我

1 个答案:

答案 0 :(得分:1)

match表达式后添加分号。

所有match臂的类型均为usize,因此,match的最终类型也是usize。您的代码有效

fn main() {
    {
        42
    }

    println!("Hi");
}
error[E0308]: mismatched types
 --> src/main.rs:3:9
  |
1 | fn main() {
  |           - expected `()` because of default return type
2 |     {
3 |         42
  |         ^^ expected (), found integer
  |
  = note: expected type `()`
             found type `{integer}`

另请参阅: