【问题标题】:What does the Rust error code E0495 mean?Rust 错误代码 E0495 是什么意思?
【发布时间】:2018-12-10 09:56:03
【问题描述】:

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

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

由于此代码使用 Rocket,因此需要 nightly 编译器。

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>

【问题讨论】:

标签: rust


【解决方案1】:

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

错误代码E0495 似乎是各种无法满足生命周期要求的不同情况的统称。该消息已经说明了这一点,并且您可以通过多种方式编写生命周期不正确匹配的代码,这可能是错误索引中没有列出示例的原因。


类型参数,包括生命周期,总是由调用者决定。查看您的特定示例,这样的函数签名:

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

意味着,对于调用者选择的 any 生命周期 'a,返回的 DynamicResponder&lt;'a&gt; 内的引用必须是有效的。但是在这种情况下,DynamicResponder&lt;'a&gt; 中的引用会是什么?它们不能是函数体中变量的引用,因为它们的生命周期与函数一样长。没有参数,所以DynamicResponder&lt;'a&gt; 唯一可以引用的东西是函数之外的东西,即静态。

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

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

【讨论】:

    猜你喜欢
    • 2015-05-18
    • 1970-01-01
    • 2015-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-05
    • 1970-01-01
    相关资源
    最近更新 更多