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

5

我又遇到了一个生命周期问题,似乎无法自行解决。

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

enter image description here

我试图按照编译器的建议,在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)
    }
}

之前我的代码已经能够正常工作,但现在我想将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>,
}

如果有好心人想要在本地编译代码,我已经将其推送到了这里的lifetime_crazyness分支中:https://github.com/cburgdorf/Floor/commits/lifetime_craziness

只需运行make floor即可编译。

1个回答

10

好的,我下载了你的代码并尝试编译。确实,如果我们查看你的Response结构体的定义,会看到这样:

OK,所以我拉下你的代码来尝试编译了。实际上,如果我们看一下你的Response结构体的定义,会发现它是这样的:

pub struct Response<'a> {
    ///the original `http::server::ResponseWriter`
    pub origin: &'a mut http::server::ResponseWriter<'a>,
}

从编译器的角度来看,这个定义声称指向 http::server::ResponseWriter 的指针的生命周期与 http::server::ResponseWriter 内部的生命周期相同。我并没有看到任何特别的理由来证明这是正确的,而且看起来编译器也无法确定这一点。因此,为了修复它,您需要引入另一个生命周期参数,以便允许生命周期是不同的可能性:

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

这是一个PR中的修复方案,链接如下:https://github.com/BurntSushi/Floor/commit/127962b9afc2779c9103c28f37e52e8d292f9ff2


1
抱歉,我搞错了问题。我指的是“响应”。但是没错,你已经弄清楚了。我稍后会更新问题。我现在正在使用手机,稍后需要重新阅读你的答案。感谢你的帮助。我很荣幸将你列为Floor的贡献者。 - Christoph
再次感谢!我已经纠正了我的问题,也修改了你的回答。不过,我有一个后续问题要问;-) http://stackoverflow.com/questions/24292831/what-do-these-both-structs-differ-in-the-way-they-are-affected-by-lifetimes - Christoph
我将提交的代码进行了重新基于语义的调整,但是将你设置为了提交的作者,因为你帮助了我。然而,如果你不想与这个提交联系在一起,因为你认为它是无意义的,请告诉我,我会将自己设置为作者。 - Christoph
啊,这里是提交 https://github.com/cburgdorf/Floor/commit/dde2d3be262b76c80950a858bc1a62f153fc72da。 - Christoph

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接