I'm trying to send Vec<Box<Trait>>
over a channel. The sending part sort of works, I guess. After recv()
ing the Vec
I'm trying to iterate over it and pass the inner value's reference to a function, which fails with an error:
error[E0277]: the trait bound `&std::boxed::Box<AwesomeTrait + std::marker::Send>: AwesomeTrait` is not satisfied
--> src/main.rs:12:13
|
12 | K::abc(&something);
| ^^^^^^ the trait `AwesomeTrait` is not implemented for `&std::boxed::Box<AwesomeTrait + std::marker::Send>`
|
note: required by `K::abc`
--> src/main.rs:57:5
|
57 | pub fn abc<T: AwesomeTrait>(something: &T) {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Is there a way to get the inner value out of the Box
somehow?
Here's a minimal reproduction.:
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel::<Request>();
let s = Something::new();
tx.send(Request::Do(s)).unwrap();
let z = thread::spawn(move || match rx.recv().unwrap() {
Request::Do(somethings) => for something in somethings.list.iter() {
K::abc(&something);
},
});
z.join();
}
pub enum Request {
Do(Something),
}
pub struct Something {
list: Vec<Box<AwesomeTrait + Send>>,
}
impl Something {
pub fn new() -> Self {
Self { list: Vec::new() }
}
pub fn from<T: AwesomeTrait + Send + 'static>(something: T) -> Self {
let mut list = Vec::with_capacity(1);
list.push(Box::new(something));
// Self { list }
Self { list: Vec::new() }
}
pub fn push<T: AwesomeTrait + Send + 'static>(&mut self, something: T) {
self.list.push(Box::new(something));
}
}
pub trait AwesomeTrait {
fn func(&self);
}
pub struct X {}
impl AwesomeTrait for X {
fn func(&self) {}
}
pub struct K {}
impl K {
pub fn abc<T: AwesomeTrait>(something: &T) {
&something.func();
}
}