首页 > 解决方案 > 请解释“由于要求冲突,无法推断借用表达式的适当生命周期”错误

问题描述

我有一个代码的小例子,我现在不明白:

use std::sync::mpsc::Sender;
use tokio::prelude::{Async, Future};

pub enum Progress<'a> {
    File(&'a str),
}

pub struct ReadAndHash<'a> {
    message: String,
    tx: Sender<Progress<'a>>,
}

pub struct FileInfo {}

impl<'a> Future for ReadAndHash<'a> {
    type Item = FileInfo;
    type Error = ();

    fn poll(&mut self) -> Result<Async<Self::Item>, Self::Error> {
        self.tx.send(Progress::File(&self.message)).unwrap();

        Ok(Async::Ready(FileInfo {}))
    }
}

以及 rust 编译结果:

error[E0495]: cannot infer an appropriate lifetime for borrow expression due to conflicting requirements
  --> src/main.rs:20:37
   |
20 |         self.tx.send(Progress::File(&self.message)).unwrap();
   |                                     ^^^^^^^^^^^^^
   |
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 19:5...
  --> src/main.rs:19:5
   |
19 | /     fn poll(&mut self) -> Result<Async<Self::Item>, Self::Error> {
20 | |         self.tx.send(Progress::File(&self.message)).unwrap();
21 | |
22 | |         Ok(Async::Ready(FileInfo {}))
23 | |     }
   | |_____^
note: ...so that reference does not outlive borrowed content
  --> src/main.rs:20:37
   |
20 |         self.tx.send(Progress::File(&self.message)).unwrap();
   |                                     ^^^^^^^^^^^^^
note: but, the lifetime must be valid for the lifetime 'a as defined on the impl at 15:6...
  --> src/main.rs:15:6
   |
15 | impl<'a> Future for ReadAndHash<'a> {
   |      ^^
   = note: ...so that the expression is assignable:
           expected Progress<'a>
              found Progress<'_>

我不知道什么是生命“'_”。你能帮我理解一下,发生了什么吗?

我的想法是将引用传递给 TX 而不是值。

标签: rustlifetime

解决方案


推荐阅读