0

Let me present you a snippet:

use serde::{Deserialize, Serialize};

pub trait Transport {
    fn send<ReqT, OkT, ErrT>(&self, req: ReqT) -> Result<OkT, Result<ErrT, ()>>
        where
            ReqT: Serialize + Send,
            OkT: for<'a> Deserialize<'a> + Default,
            ErrT: for<'a> Deserialize<'a>,
            Self: Sized + Sync + Send + 'static;
}

pub struct MyTransport {}

impl Transport for MyTransport {
    fn send<ReqT, OkT, ErrT>(&self, req: ReqT) -> Result<OkT, Result<ErrT, ()>>
        where
            ReqT: Serialize + Send,
            OkT: for<'a> Deserialize<'a> + Default,
            ErrT: for<'a> Deserialize<'a>,
            Self: Sized + Sync + Send + 'static,
    {
        Ok(OkT::default())
    }
}

pub struct Proc<'a> {
    pub transport: &'a (dyn Transport + Send + Sync + 'static),
}

impl Proc<'_> {
    pub fn enable(&self, asset: String) {
        let _ = self.transport
            .send::<_, i32, i32>(asset);
    }
}

fn main() {
    let t = MyTransport{};
    let proc = Proc {transport: &t};
    proc.enable(String::default());
}

that does not compiled with the following error:

   Compiling playground v0.0.1 (/playground)
error: the `send` method cannot be invoked on a trait object
  --> src/lib.rs:33:14
   |
9  |             Self: Sized + Sync + Send + 'static;
   |                   ----- this has a `Sized` requirement
...
33 |             .send::<_, i32, i32>(asset);
   |              ^^^^

How can I overcome this?

Playground

cafce25
  • 15,907
  • 4
  • 25
  • 31
  • 1
    For your example I recommend you use a proper type parameter instead of a dynamic trait object `pub struct Proc<'a, T> { pub transport: &'a T, }`, for any other advice you'd have to provide a more thorough [description of your actual problem, not how you tried to solve it](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). – cafce25 Apr 07 '23 at 10:07

0 Answers0