首页 文章

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

提问于
浏览 1029
1

我正在使用Rocket创建一个Web服务器,我正在尝试围绕 Responder trait创建一个包装器,以便我的路由方法可以返回任何结构 .

下面的代码不能编译,因为我不完全理解有关生命周期的错误 . 错误是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 回答

  • 1

    类型:

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

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

    我不完全确定为什么 'a 不仅仅被推断为 'static ,但是自己做出改变会解决它:

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

    遗憾的是,您仍然会遇到此代码的问题,因为 respond_to 消耗 self ,但需要在未知大小的特征对象上调用它 .

相关问题