Rust错误代码E0495代表什么?

3
我正在使用Rocket制作一个Web服务器,并试图在Responder特质周围创建一个包装器,以便我的路由方法可以返回任何结构体。
以下代码无法编译,因为存在关于生命周期的错误,我不完全理解。错误是未在错误索引中列出;它跳过了E0492E0496
由于此代码使用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>

总的来说,您试图欺骗编译器,因为您声称route的调用者可以提供任何他们想要的生命周期,但您始终返回特定的生命周期。请参见“Expected type parameter” error in the constructor of a generic struct,了解类型参数的相同概念。 - Shepmaster
1个回答

4
Rust错误码E0495是什么意思?
错误码E0495似乎是一个捕获无法协调生命周期要求的各种不同情况的总称。信息已经表示了这一点,而且您可能会编写大量代码,其中生命周期不能正确匹配,这也许是为什么它没有在错误索引中列出示例的原因。
类型参数(包括生命周期)始终由调用方确定。查看您的特定示例,函数签名如下:
fn route<'a>() -> DynamicResponder<'a> { ... }

意味着对于调用者选择的'a生命周期,返回的DynamicResponder<'a>内部的引用必须是有效的,不论生命周期长短。但是,在这种情况下,DynamicResponder<'a>内部的引用到底是什么呢?它们不能是函数体内变量的引用,因为这些变量只能存在于函数的生命周期内。没有参数,所以DynamicResponder<'a>引用的唯一可能是在函数外部存在的东西,即静态变量。

您可以通过删除生命周期变量并将生命周期参数设置为唯一有意义的生命周期来修复错误:

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

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