Async_trait dyn trait error

use anyhow::{anyhow, Result};
use async_trait::async_trait;
#[async_trait]
pub trait Fetch {
type Error;
async fn fetch(&self) -> Result<(), Self::Error>;
}

pub struct foo;

#[async_trait]
impl Fetch for foo {
type Error = anyhow::Error;

async fn fetch(&self) -> Result<(), Self::Error> {
    Err(anyhow!("hahha"))
}

}

pub struct bar;

#[async_trait]
impl Fetch for bar {
type Error = anyhow::Error;

async fn fetch(&self) -> Result<(), Self::Error> {
    Err(anyhow!("wowo"))
}

}

async fn todo(t: &dyn Fetch) -> Result<()> {
Ok(t.fetch().await?)
}

#[tokio::main]
async fn main() -> Result<()> {
let foo1 = foo;
let x = todo(&foo1).await?;

Ok(())

}


how to sloved this?

One possibility is to define the error type:

async fn todo(t: &dyn Fetch<Error = anyhow::Error>) -> Result<(), anyhow::Error> {

see this in the rust playground

1 Like

greate! thank you very much

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.