我搜索了互联网,试图找到co_await操作员的工作,但我仍然不明白。我猜下面的代码:
co_await foo();
Run Code Online (Sandbox Code Playgroud)
暂停协程直到foo完成,但是在这种情况下,它不同于简单的调用,foo例如:
foo();
Run Code Online (Sandbox Code Playgroud)
这还将暂停当前功能,直到foo完成。请给我解释一下。
我有一个枚举:
enum T {
A(String),
}
Run Code Online (Sandbox Code Playgroud)
我想匹配此枚举的变量,但此代码不起作用:
match t {
T::A("a") => println!("a"),
T::A("b") => println!("b"),
_ => println!("something else"),
}
Run Code Online (Sandbox Code Playgroud)
我知道我可以做到这一点,但在我看来它太冗长了:
match t {
T::A(value) => match value.as_ref() {
"a" => println!("a"),
"b" => println!("b"),
_ => println!("something else"),
},
}
Run Code Online (Sandbox Code Playgroud)
有没有更短的方法来做到这一点?
我有以下代码:
use std::collections::HashMap;
trait T: Sized {}
struct A;
impl T for A {}
fn main() {
let h: HashMap<String, T>;
}
Run Code Online (Sandbox Code Playgroud)
但编译器抱怨:
error[E0277]: the trait bound `T: std::marker::Sized` is not satisfied
--> src\main.rs:10:12
|
10 | let h: HashMap<String, T>;
| ^^^^^^^^^^^^^^^^^^ `T` does not have a constant size known at compile-time
|
= help: the trait `std::marker::Sized` is not implemented for `T`
= note: required by `std::collections::HashMap`
error[E0038]: the trait `T` cannot be made into an object
--> …Run Code Online (Sandbox Code Playgroud) 我有一个像这样的枚举:
#[derive(Debug, Deserialize, Serialize)]
enum E {
A(i32),
#[serde(skip)]
B(bool),
C(char),
D(Vec<i32>),
}
Run Code Online (Sandbox Code Playgroud)
然后我尝试使用bincode crate执行以下操作:
fn main() {
let data = E::C('A');
let encoded = bincode::serialize(&data).unwrap();
let decoded = bincode::deserialize::<E>(&encoded).unwrap();
println!("{:?}", decoded);
}
Run Code Online (Sandbox Code Playgroud)
然而,这会引发以下消息:
Run Code Online (Sandbox Code Playgroud)#[derive(Debug, Deserialize, Serialize)] enum E { A(i32), #[serde(skip)] B(bool), C(char), D(Vec<i32>), }
我注意到,如果满足以下条件之一,则一切正常:
#[serde(skip)]属性我还了解 bincode 以某种方式忽略#[serde(skip)]并尝试反序列encoded化为E::D(Vec<i32>). 如果我更改Vec<i32>为char它会起作用,但decoded会E::D('A')(而不是E::C('A'))。
我错过了什么还是 bincode 箱中的错误?
我在Rust写了一个echo服务器和客户端.这是我的代码:
服务器:
use std::net::{TcpListener, TcpStream};
use std::thread;
use std::io::Write;
use std::io::BufReader;
use std::io::BufRead;
use std::io::BufWriter;
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();
writer.write(s.as_bytes()).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());
});
}
}
Run Code Online (Sandbox Code Playgroud)
客户:
use std::net::TcpStream;
use std::io;
use std::io::Write;
use std::io::BufReader;
use std::io::BufRead;
use std::io::BufWriter;
fn main() …Run Code Online (Sandbox Code Playgroud)