3
#[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?

Elias Holzmann
  • 3,216
  • 2
  • 17
  • 33
cactus
  • 357
  • 4
  • 16
  • 1
    After fixing syntax errors and type mismatches, it seems to work - https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=4e0f806d715f4f7c5b07f828f36bba4c. Could you make a reproducible example? – Cerberus Apr 25 '21 at 06:32
  • @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 :) – cactus Apr 25 '21 at 06:47

1 Answers1

3

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
}
Cerberus
  • 8,879
  • 1
  • 25
  • 40