你可能还在为Rust的思维转换而苦苦挣扎,现在我有这样一个使用场景 - 一个多线程TcpListener
的配置:
use std::net::{TcpListener, TcpStream, ToSocketAddrs};
use std::thread;
fn main() {
serve("127.0.0.1:3333", Configuration { do_something: true });
}
//#[derive(Copy, Clone)]
pub struct Configuration {
pub do_something: bool,
}
pub fn serve<A: ToSocketAddrs>(addr: A, conf: Configuration) {
let listener = TcpListener::bind(addr).expect("bind failed");
for stream in listener.incoming() {
match stream {
Ok(stream) => {
thread::spawn(move || {
handle_client(stream, &conf);
});
}
Err(e) => {
println!("Connection failed: {}", e);
}
}
}
}
fn handle_client(stream: TcpStream, conf: &Configuration) {
if conf.do_something {
//stream....
}
}
我很高兴看到
TcpStream
已被handle_client
使用,这正是它的用途,但为什么每个线程都要复制Configuration
呢?我希望只有一份拷贝,并与所有线程共享不可变引用。是否可能?或者我可能没有理解重点。如果我通过引用传递
Configuration
,那么为什么还需要Copy
和Clone
特性呢?这让我感到困惑。error[E0382]: capture of moved value: `conf`
--> src/main.rs:19:64
|
19 | thread::spawn(move || { handle_client(stream, &conf); });
| ------- ^^^^ value captured here after move
| |
| value moved (into closure) here
|
= note: move occurs because `conf` has type `Configuration`, which does not implement the `Copy` trait