Search code examples
rustserderust-rocket

the trait `Serialize` is not implemented for <'_>


#[derive(serde::Serialize)]
struct IndexLink<'r>{
    text: &'r str,
    link: &'r str;
}

#[derive(serde::Serialize)]
struct IndexContext<'r> {
    title: &'r str,
    links: Vec<&'r IndexLink<&'r>>
}

#[get("/")]
pub fn index() -> Template {
    Template::render("index", &IndexContext{
        title : "My home on the web",
        links: vec![IndexLink{text: "About", link: "/about"}, IndexLink{text: "RSS Feed", link: "/feed"}]
    })
}

causes error[E0277]: the trait bound IndexContext<'_>: Serialize is not satisfied. The error occurs from the line adding the vec of IndexLink's to the IndexContent when rendering the template. I must be doing something wrong with the lifetimes.

Why is this error happening?


Solution

  • The code in question has multiple syntax errors. The valid way to define these types seems to be the following:

    #[derive(serde::Serialize)]
    struct IndexLink<'r>{
        text: &'r str,
        link: &'r str, // no semicolon inside struct definition
    }
    
    #[derive(serde::Serialize)]
    struct IndexContext<'r> {
        title: &'r str,
        links: Vec<&'r IndexLink<'r>>, // lifetime parameter is just 'r, not &'r
    }