title: Spawn non-static future with Tokio
body: <p>I have an async method that should execute some futures in parallel, and only return after all futures finished. However, it is passed some data by reference that does not live as long as <code>'static</code> (it will be dropped at some point in the main method). Conceptually, it's similar to this (<a href="https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2018&amp;gist=4387f1157b95493e56b033a87c4e0d42" rel="nofollow noreferrer">Playground</a>):</p>
  <pre class="lang-rust prettyprint-override"><code>async fn do_sth(with: &amp;u64) {
      delay_for(Duration::new(*with, 0)).await;
      println!(&quot;{}&quot;, with);
  }
  
  async fn parallel_stuff(array: &amp;[u64]) {
      let mut tasks: Vec&lt;JoinHandle&lt;()&gt;&gt; = Vec::new();
      for i in array {
          let task = spawn(do_sth(i));
          tasks.push(task);
      }
      for task in tasks {
          task.await;
      }
  }
  
  #[tokio::main]
  async fn main() {
      parallel_stuff(&amp;[3, 1, 4, 2]);
  }
  </code></pre>
  <p>Now, tokio wants futures that are passed to <code>spawn</code> to be valid for the <code>'static</code> lifetime, because I could drop the handle without the future stopping. That means that my example above produces this error message:</p>
  <pre><code>error[E0759]: `array` has an anonymous lifetime `'_` but it needs to satisfy a `'static` lifetime requirement
    --&gt; src/main.rs:12:25
     |
  12 | async fn parallel_stuff(array: &amp;[u64]) {
     |                         ^^^^^  ------ this data with an anonymous lifetime `'_`...
     |                         |
     |                         ...is captured here...
  ...
  15 |         let task = spawn(do_sth(i));
     |                    ----- ...and is required to live as long as `'static` here
  </code></pre>
  <p>So my question is: How do I spawn futures that are only valid for the current context that I can then wait until all of them completed?</p>