如何修复:无法推断自动强制的适当生命周期

Chr*_*oph 5 lifetime rust

我设法再次遇到一个终身问题,我似乎无法自己解决.

编译器告诉我无法推断自动强制的适当生命周期

在此输入图像描述

我试图遵循编译器建议并在handle_request方法中引入了生命周期注释.

fn handle_request<'a>(&self, req: &Request, res: &'a mut ResponseWriter) {


    fn set_headers(req: &Request, res: &mut ResponseWriter) {
        //probably not important for the example 
    }

    match &req.request_uri {
        &AbsolutePath(ref url) => {
            match self.router.match_route(req.method.clone(), url.clone()) {
                Some(route_result) => { 
                    set_headers(req, res); 

                    let floor_req = request::Request{
                        origin: req,
                        params: route_result.params.clone()
                    };

                    let floor_res = response::Response{
                        origin: res
                    };

                    (route_result.route.handler)(floor_req, &mut floor_res);
                },
                None => {}
            }
        },
        _ => set_headers(req, res)
    }
}
Run Code Online (Sandbox Code Playgroud)

我之前有代码工作,但现在我想http::server::ResponseWriter在我自己的Response结构中包装.我之前做的完全一样,Request但就生命周期而言,情况似乎略有不同.也许是因为它&mut不仅仅是一个简单的&参考.

这是我的ResponseWriter结构.

use http;

///A container for the response
pub struct Response<'a> {
    ///the original `http::server::ResponseWriter`
    pub origin: &'a mut http::server::ResponseWriter<'a>,
}
Run Code Online (Sandbox Code Playgroud)

只是想让任何Samaritan想要在本地编译代码,我把它推入了lifetime_crazyness分支:https://github.com/cburgdorf/Floor/commits/lifetime_craziness

只是运行make floor来编译它.

Bur*_*hi5 10

好的,所以我下载了你的代码来尝试编译它.实际上,如果我们看一下你的Responsestruct 的定义,我们会看到:

pub struct Response<'a> {
    ///the original `http::server::ResponseWriter`
    pub origin: &'a mut http::server::ResponseWriter<'a>,
}
Run Code Online (Sandbox Code Playgroud)

从编译器的角度来看,这个定义声称该指针的寿命http::server::ResponseWriter相同的任何寿命的内部http::server::ResponseWriter.我没有看到任何特殊原因,为什么这应该是真的,看起来编译器也不能.因此,要修复它,您需要引入另一个生命周期参数,以便您可以确定生命周期是不同的:

pub struct Response<'a, 'b> {
    ///the original `http::server::ResponseWriter`
    pub origin: &'a mut http::server::ResponseWriter<'b>,
}
Run Code Online (Sandbox Code Playgroud)

这是PR中的修复程序:https://github.com/BurntSushi/Floor/commit/127962b9afc2779c9103c28f37e52e8d292f9ff2