2

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

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
prograe69
  • 23
  • 2

1 Answers1

3

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:

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • Thanks, its working now! But it was pretty confusing to add the semicolon there, i'll guess i have to read more on this topic – prograe69 Jun 03 '19 at 15:07
  • 2
    @prograe69: This is the difference between an *expression* which produces a value, and a *statement* which does not. Since the goal of an expression is to produce a value, it is unexpected when that value is unused. `;` transforms signals the intent of the programmer: it transforms the expression in a statement as a way of saying "I know it produces a value, I just don't care about it, throw it away". – Matthieu M. Jun 04 '19 at 11:16