[英]What does “expected type `()`” mean on a match expression?
I'm rewriting a simple TCP based server to experiment with Rust.我正在重写一个简单的基于 TCP 的服务器来试验 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我在网上找不到解决这个问题的方法,
rustc --explain
也没有帮助我
Add a semicolon after your match
expression.在
match
表达式后添加分号。
The type of all of the match
arms is usize
, so the resulting type of the match
is also a usize
.所有
match
武器的类型都是usize
,因此match
的结果类型也是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:也可以看看:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.