2
votes

I want to create a Vec<T> where T is bound to a trait called HTML:

pub trait HTML {
    fn to_email_body(&self) -> String;
}

Now I want to have a struct with:

impl Body {
pub fn new(from: String, to: Vec<String>, components: Vec<C>) -> Self 
    where C: HTML 
    {
        Self {
            from,
            to,
            components,
        }
    }
}

So I can pass components with a generic type T to the new constructor.

However, I have to create a Vec<&dyn HTML> so Rust can size it during compile time:

let mut components: Vec<&dyn HTML> = Vec::new();
components.push(&dashboard);

How would a trait impl look like for this? So far I have

impl HTML for Dashboard {
    fn to_email_body(&self) -> String {
        format!("{}", self)
    }
}

And now I am getting the following error:

the trait bound `&dyn HTML: HTML` is not satisfied
the trait `HTML` is not implemented for `&dyn HTML`

I somehow can't make the connection on where I have to define the &dyn part of the trait/trait impl!

1

1 Answers

5
votes

dyn HTML implements HTML, &dyn HTML doesn't. Either change Body::new to take Vec<&C> where C: HTML, or add a blanket implementation of HTML for references:

impl<T: HTML> HTML for &T {
    fn to_email_body(&self) {
        self.to_email_body()
    }
}