Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

rust - What does "expected type `()`" mean on a match expression?

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());
        });
    }
}

And the error:

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Add a semicolon after your match expression.

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

See also:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...