0
votes

This is a follow up question to: How to fix: cannot infer an appropriate lifetime for automatic coercion.

I wonder why do these both structs differ in the way they are affected by lifetimes.

Example 1

use http;

pub struct Request<'a> {
    pub origin: &'a http::server::Request,
}

Example 2

use http;

pub struct Response<'a, 'b> {
    pub origin: &'a mut http::server::ResponseWriter<'b>,
}

They look pretty much similar to me except that the second one holds a mutable reference whereas the first one holds an immutable reference.

However, for Example 2 I can't just use a lifetime for the reference. I must give a lifetime for the struct as well.

So, I wonder is there something inside the struct that causes such behavior or is it really because the one in the second example is a mutable reference. And if so, why exactly does that cause that.

1
"However, for Example 2 I can't just use a lifetime for the reference. I must give a lifetime for the struct as well." You mean that you can't omit <'b> after ResponseWriter? In this case it happens because ResponseWriter is parameterized by a lifetime, while Request is not. It is similar to that you have to write Option<int> with a parameter but String without one.Vladimir Matveev
If you inspect the definition of ResponseWriter, you will find that it contains a reference. I'm guessing that it's this ResponseWriter: rust-ci.org/chris-morgan/rust-http/doc/http/server/response/…A.B.
Ah, brilliant. It's parameterized by a lifetime in it's definition. So I have to take that into account. Makes sense! If anyone cares to add it as an answer, I'll be happy to accept it :)Christoph
(As a general rule, if you have just a slight extra question—this was just a request for clarification—it’s best to keep it in the same question.)Chris Morgan

1 Answers

2
votes

&'a T means that you have a reference to a T object which is valid for the lifetime'a.

T<'b> means a T object containing an object inside itself valid for the lifetime 'b, as in struct T<'b> { t: &'b U }.

&'a T<'b>is thus a reference with lifetime 'a to a T<'b> object.

In the case of the ResponseWriter, it contains references to the Request and to the TcpStream, whereas the Request does not contain any references.