How to return a future combinator with `&self`

点点圈 提交于 2019-11-29 14:43:27

How to return a future combinator with &self

You return a future that refers to self like this:

use futures::future::{self, FutureResult}; // 0.1.28

struct Example {
    age: i32,
}

impl Example {
    fn make_a_future(&self) -> FutureResult<&Example, ()> {
        future::ok(self)
    }
}

As discussed in the Tokio documentation on returning futures, the easiest stable solution to returning a complicated future is a impl Trait. Note that we assign an explicit lifetime to self and use that in the returned value (via + 'a):

use futures::{future, Future}; // 0.1.28

struct Example {
    age: i32,
}

impl Example {
    fn make_a_future<'a>(&'a self) -> impl Future<Item = i32, Error = ()> + 'a {
        future::ok(self).map(|ex| ex.age + 1)
    }
}

Your real question is "how can I lie to the compiler and attempt to introduce memory unsafety into my program?"

Box<SomeTrait + 'static> (or Box<SomeTrait> by itself) means that the trait object must not contain any references that do not last for the entire program. By definition, your Example struct has a shorter lifetime than that.

This has nothing to do with futures. This is a fundamental Rust concept.

There are many questions that ask the same thing in regards to threads, which have similar restrictions. A small sampling:

Like in those cases, you are attempting to share a reference to a variable with something that may exist after the variable is destroyed. Languages such as C or C++ would let you do this, only to have your program crash at a seemingly random point in time in the future when that variable is accessed after being freed. The crash is the good case, by the way; information leaks or code execution is also possible.

Like the case for threads, you have to ensure that this doesn't happen. The easiest way is to move the variable into the future, not sharing it at all. Another option is to use something like an Arc around your variable, clone the Arc and hand the clone to the future.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!