【问题标题】:"Error E0477: the type does not fulfill the required lifetime" with Actix-Web handlersActix-Web 处理程序的“错误 E0477:类型不满足所需的生命周期”
【发布时间】:2018-05-04 01:08:05
【问题描述】:

我正在尝试使用 Actix-Web 实现 HTTP 请求处理程序。这是我的代码的相关部分:

impl<S> Handler<S> for FooBarHandler {
    type Result = Box<Future<Item = HttpResponse, Error = Error>>;

    fn handle(&mut self, req : HttpRequest<S>) -> Self::Result {
        req.json().from_err().and_then(|foo : Foo|
            self.baz.qux(foo);
            Ok(HttpResponse::Ok().finish())
        }).responder()
    }
}

但是,我收到以下错误消息:

error[E0477]: the type  `mymod::futures::AndThen<mymod::futures::future::FromErr<mymod::actix_web::dev::JsonBody<mymod::actix_web::HttpRequest<S>, mymod::Foo>, mymod::actix_web::Error>, std::result::Result<mymod::actix_web::HttpResponse, mymod::actix_web::Error>, [closure@src/mymod.rs:53:40: 56:10 self:&&mut mymod::FooBarHandler]>` does not fulfill the required lifetime
  --> src/mymod.rs:56:12
   |
56 |         }).responder()
   |            ^^^^^^^^^
   |
   = note: type must satisfy the static lifetime

我完全不明白这个错误信息。该代码实际上与this example 相同,不包含任何生命周期注释。

【问题讨论】:

  • 正如目前提出的,这个问题是题外话:寻求调试帮助的问题(“为什么这段代码不起作用?”)必须包括所需的行为、特定的问题或错误以及在问题本身中重现它所需的最短代码。您还没有提供FooBarHandler 的定义,您还没有显示您正在导入的箱子(及其版本!)等等。事实上,您的代码在语法上无效

标签: rust rust-actix


【解决方案1】:

您在 .and_then 未来中使用 self,这违反了生命周期要求。

【讨论】:

  • 我应该如何避免这种情况?我尝试在and_then 未来之前添加let baz = self.baz.clone();,然后用baz 替换self.baz,但这给出了以下错误:error[E0373]: closure may outlive the current function, but it borrows baz, which is owned by the current function
  • 克隆然后将其移动到闭包,.and_then(move |..| {...})
  • 我试过了,但我得到了这些错误:The parameter type 'S' may not live long enough。编译器建议添加一个显式的生命周期边界-S : 'static,但这会导致无法在线程之间安全共享 trait 的错误。
猜你喜欢
  • 2016-01-31
  • 2018-02-12
  • 1970-01-01
  • 2011-03-20
  • 1970-01-01
  • 2018-12-06
  • 2018-12-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多