Reputation: 2127
I am writing a multithreaded webserver and basically I need to copy a Vec<Handler>
of user-provided handler objects across multiple threads on server startup. I tried several approaches:
1) Define Handler as a trait with a fn process(&mut self, Request) -> Response
method. Users would implement it for each handler struct. This approach is very common in languages like C++ or python. The problem is that rust doesn't allow me to copy or clone a trait object as it would imply the Sized
bound on it which is forbidden on trait objects.
2) Define Handler as a Box<FnMut(Request) -> Response>
. This doesn't work as closures are not copyable.
3) I could share the same objects between threads but this makes very little sense to me as I would need a mutex which would introduce useless contention when I actually just need separate copies across threads.
How can I implement this properly?
Upvotes: 1
Views: 111
Reputation: 299890
The simplest solution is to request the user to define a clone method.
trait Handler {
fn process(&mut self, r: Request) -> Response;
fn duplicate(&self) -> Box<Handler>;
}
And then you can copy your Vec<Box<Handler>>
quite easily.
Upvotes: 1