Hello everyone,
use std::sync::Arc;
fn send_to_thread(obj: Arc<dyn Trait>) {}
trait Trait {
fn update(&mut self);
}
struct Foo{}
impl Trait for Foo {
fn update(&mut self){}
}
pub fn new_obj() -> Arc<dyn Trait> {
Arc::new(Foo{})
}
fn main() {
let mut foo: Arc<dyn Trait> = new_obj();
foo.update(); // Obviously can't mutate behind Arc
send_to_thread(foo);
}
Here's the deal. I need to
- Create a
dyn Trait
. - Update(initialize) it once.
- Sent to threads.
My options:
- Fully initialize object in
new_obj
- Possible, butnew_obj
would have been greatly complicated. - Return
Box<dyn Trat>
but since I need anArc
, converting to Arc needs to reallocate. Not good. - Wrap it in Arc<Mutex> - An overkill, I'm not going to mutate object in threads.
I'm seeking to have the least overhead because it's in a hot loop.
Appreciate any advice.