1

I'm trying to store different async functions in a Vec within a struct.

I've tried different things like using Box<Fn -> Future<Output = ...>>, to fall into dynamic dispatch and also wrap Output into Box<dyn>. But I get this error all the time: expected opaque type, found a different opaque type.

Here's my last tentative solution to the problem:

use futures::Future;
//use futures::prelude::TryFuture;

struct Failure<A> {
    data: A,
}

async fn add(data: u8) -> Result<u8, Failure<u8>> {
    Ok(data + 1)
}

async fn add2(data: u8) -> Result<u8, Failure<u8>> {
    Ok(data + 2)
}


struct Transaction<A, T>
where
    T: Future<Output = Result<A, Failure<A>>>,
{
    steps: Vec<Step<A, T>>,
}
struct Step<A, T>
where
    T: Future<Output = Result<A, Failure<A>>>,
{
    c: fn(A) -> T,
}

fn main() {
    Transaction {
        steps: vec![
            Step { c: add },
            Step { c: add2 }
        ],
    };
}

playground

This code fails to compile:

  --> src/main.rs:34:23
   |
34 |             Step { c: add2 }
   |                       ^^^^ expected opaque type, found a different opaque type
   |
   = note: expected fn pointer `fn(_) -> impl core::future::future::Future`
                 found fn item `fn(_) -> impl core::future::future::Future {add2}`
   = note: distinct uses of `impl Trait` result in different opaque types

How do I make it compile?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
NotBad4U
  • 1,502
  • 1
  • 16
  • 23
  • 1
    [The duplicate(s) applied to your situation](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=8193c67678c354502b4ba0e33ba2b306). – Shepmaster Mar 11 '20 at 20:20
  • Yeah sorry, the first time I only saw [How can I store an async function in a struct and call it from a struct instance?](https://stackoverflow.com/questions/58173711/how-can-i-store-an-async-function-in-a-struct-and-call-it-from-a-struct-instance) which was the solution. But the others work for my problem, thank a lot @Shepmaster ! – NotBad4U Mar 11 '20 at 20:23
  • 2
    Yep; the Stack Overflow interface only allows marking a question as a single duplicate, then adding more duplicates in a second operation, so there's a small period of time inbetween. – Shepmaster Mar 11 '20 at 20:25

0 Answers0