Rust (reference)在这里被捕获,要求它的寿命与';静止的`

Rust (reference)在这里被捕获,要求它的寿命与';静止的`,rust,Rust,我试图理解生命是如何运作的,我举了一个例子: use std::future::Future; use std::pin::Pin; use futures::future::{BoxFuture, FutureExt}; struct Message{} struct Client{} impl Client { fn send_and_expect( & mut self, message: & Message ) -&g

我试图理解生命是如何运作的,我举了一个例子:

use std::future::Future;
use std::pin::Pin;
use futures::future::{BoxFuture, FutureExt};

struct Message{}

struct Client{}

impl Client {
    fn send_and_expect(
        & mut self,
        message: & Message
    ) -> Pin<Box<(dyn futures::Future<Output = std::result::Result<(), ()>> + std::marker::Send )>> {
        async move {
            let m = message;
            Ok(())
        }.boxed()
    }
}
我一直认为它必须活得和被钉住的返回值一样长。不一定是静态的

我知道给你一个特定的生命


这是因为返回的未来将保留对参数的捕获,因此参数必须在未来生存,并且
Box
隐式具有
'静态
生存期,除非
T
受到生存期标识符的约束。 如果将返回类型的生存期约束为与参数的生存期匹配,则它可能会编译

impl客户端{

fn send_和_expect Pin这是因为返回的future保持对参数的捕获,因此参数必须比future更长寿,
Box
隐式地具有一个
'静态
生存期,除非
T
受生存期标识符的约束。 如果将返回类型的生存期约束为与参数的生存期匹配,则它可能会编译

impl客户端{

fn send_和_expectpin示例中没有
&request
,您的意思是
&Message
?请阅读整个错误消息。由于返回类型的原因,它需要满足
&static
。如果更改返回类型,它将起作用。@Deadbeef是的,但我应该使用哪种返回类型?示例中没有
&request
,do您的意思是
&Message
?请阅读整个错误消息。由于您的返回类型,它需要满足
&'static
。如果您更改返回类型,它将起作用。@是的,但我应该使用哪种返回类型?
error[E0759]: `message` has an anonymous lifetime `'_` but it needs to satisfy a `'static` lifetime requirement
  --> src/lib.rs:14:20
   |
12 |           message: & Message
   |                    --------- this data with an anonymous lifetime `'_`...
13 |       ) -> Pin<Box<(dyn futures::Future<Output = std::result::Result<(), ()>> + std::marker::Send )>> {
14 |           async move {
   |  ____________________^
15 | |             let m = message;
16 | |             Ok(())
17 | |         }.boxed()
   | |_________^ ...is captured here, requiring it to live as long as `'static`
   |
help: to declare that the trait object captures data from argument `message`, you can add an explicit `'_` lifetime bound
   |
13 |     ) -> Pin<Box<(dyn futures::Future<Output = std::result::Result<(), ()>> + std::marker::Send + '_ )>> {
   |                                                                                                 ^^^^