Rust错误代码E0495是什么意思?

时间:2018-12-10 09:56:03

标签: rust

我正在使用Rocket来构建Web服务器,并且试图围绕Responder特性进行包装,以便我的route方法可以返回任何结构。

下面的代码由于我不完全了解的关于生存期的错误而无法编译。错误是not listed in the error index;从E0492跳到E0496。

由于此代码使用了Rocket,因此需要每晚进行编译。

main.rs

#![feature(custom_attribute, proc_macro_hygiene, decl_macro)]
#[macro_use]
extern crate rocket;
extern crate rocket_contrib;

use rocket::{http::Status, response::Responder, Request};
use rocket_contrib::templates::Template;

fn main() {
    rocket::Rocket::ignite().mount("/", routes![route]).launch();
}

#[get("/")]
fn route<'a>() -> DynamicResponder<'a> {
    DynamicResponder::from(Template::render("template", ()))
}

struct DynamicResponder<'a> {
    inner: Box<dyn Responder<'a> + 'a>,
}

impl<'r> DynamicResponder<'r> {
    pub fn from<T: 'r>(responder: T) -> DynamicResponder<'r>
    where
        T: Responder<'r>,
    {
        DynamicResponder {
            inner: Box::new(responder),
        }
    }
}

impl<'r> Responder<'r> for DynamicResponder<'r> {
    fn respond_to<'b>(
        self,
        request: &'b Request,
    ) -> Result<rocket::response::Response<'r>, Status> {
        self.inner.respond_to(request)
    }
}

Cargo.toml

[package]
name = "rocketing_around"
version = "0.1.0"

[dependencies]
rocket = "0.4.0"

[dependencies.rocket_contrib]
version = "0.4.0"
default_features = false
features = [ "handlebars_templates" ]

编译器消息:

error[E0495]: cannot infer an appropriate lifetime for lifetime parameter `'r` due to conflicting requirements
  --> src/main.rs:15:5
   |
15 |     DynamicResponder::from(Template::render("template", ()))
   |     ^^^^^^^^^^^^^^^^^^^^^^
   |
note: first, the lifetime cannot outlive the lifetime 'a as defined on the function body at 14:10...
  --> src/main.rs:14:10
   |
14 | fn route<'a>() -> DynamicResponder<'a> {
   |          ^^
   = note: ...so that the expression is assignable:
           expected DynamicResponder<'a>
              found DynamicResponder<'_>
   = note: but, the lifetime must be valid for the static lifetime...
   = note: ...so that the types are compatible:
           expected rocket::response::Responder<'_>
              found rocket::response::Responder<'static>

1 个答案:

答案 0 :(得分:1)

类型:

fn route<'a>() -> DynamicResponder<'a> { ... }

表示该函数保证返回的DynamicResponder有效至少与'a一样。但是'a是由调用者选择的,因此它必须在 any 生存期内有效,即'a: 'static。这就是为什么消息中的第二个注释指的是静态寿命。

我不确定为什么'a不仅仅被推论为'static,但您自己进行更改会解决该问题:

fn route() -> DynamicResponder<'static> { ... }

不幸的是,由于respond_to消耗了self,因此您仍然会在此代码上遇到问题,但是需要在未知大小的特征对象上调用它。