Why should I specify a lifetime annotation when typing a struct in a function declaration?

Viewed 167

"The Rust Programming Language" shows the following example of using lifetime annotations with a function:

fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
    if x.len() > y.len() {
        x
    } else {
        y
    }
}

If I want to call such a function, I can just call it without anything special. If I want to define a struct, I can do a similar thing:

#[derive(Deserialize, Debug)]
struct News<'a> {
    title: &'a str,
    text: &'a str
}

But when using it, as in this example of rocket route, I have to "type" the struct with lifetime annotation

#[get("/submit", data = "<n>")]
async fn submit(n: Json<News<'_>>) -> Status {
    print!("{:#?}", n);
    Status::Ok
}

Why do I have to add these "types" when writing a signature? It looks like something compiler can (as when I call a function) figure out by itself. Am I missing something?

0 Answers
Related