1
votes
#[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?

1
After fixing syntax errors and type mismatches, it seems to work - play.rust-lang.org/…. Could you make a reproducible example?Cerberus
@Cerberus I just tried your code and it worked. As far as I can tell you only changed Vec<&'r IndexLink<&'r>> to Vec<&'r IndexLink<'r>>? Thanks though, if you post as an answer I will accept it :)636f6e6f7262726f73

1 Answers

1
votes

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
}