【发布时间】:2018-06-12 19:48:46
【问题描述】:
我正在尝试通过频道发送Vec<Box<Trait>>。我猜,发送部分有点用。在recv()Vec 之后,我试图对其进行迭代并将内部值的引用传递给一个函数,该函数失败并出现错误:
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) {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
有没有办法以某种方式从Box 中获取内部价值?
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();
}
}
【问题讨论】:
-
相信When should I not implement a trait for references to implementors of that trait?的问答已经回答了你的第一个问题。如果您不同意,请edit您的问题解释差异。否则,我们可以将此问题标记为已回答。
-
谢谢,您的第一条评论解决了第二个问题!我会编辑掉问题的那一部分,但我仍然不确定如何解决第一部分,即使你链接了那个建议。
标签: rust