【发布时间】:2021-10-20 12:18:32
【问题描述】:
我想创建一个Vec<T>,其中T 绑定到一个名为HTML 的特征:
pub trait HTML {
fn to_email_body(&self) -> String;
}
现在我想要一个结构体:
impl Body {
pub fn new(from: String, to: Vec<String>, components: Vec<C>) -> Self
where C: HTML
{
Self {
from,
to,
components,
}
}
}
所以我可以将带有泛型类型T 的components 传递给new 构造函数。
但是,我必须创建一个 Vec<&dyn HTML> 以便 Rust 可以在编译期间调整它的大小:
let mut components: Vec<&dyn HTML> = Vec::new();
components.push(&dashboard);
trait impl 看起来会是什么样子?到目前为止我有
impl HTML for Dashboard {
fn to_email_body(&self) -> String {
format!("{}", self)
}
}
现在我收到以下错误:
the trait bound `&dyn HTML: HTML` is not satisfied
the trait `HTML` is not implemented for `&dyn HTML`
我无法在我必须定义 trait/trait impl 的 &dyn 部分的地方建立联系!
【问题讨论】: