{ data: T } impl Message for M" /> { data: T } impl Message for M" /> { data: T } impl Message for M"/>

How to define a generic data type as Message in actix

499 Views Asked by At

Is there a way to write this code with #[derive(Message)] and #[rtype(result = "...")].

pub struct MyMsg<T> {
    data: T
}

impl<T: 'static> Message for MyMsg<T> {
    type Result = Result<MyMsg<T>, Error>;
}

I tried this but the compiler complains about the required lifetime bounds.

#[derive(Message)]
#[rtype(result = "Result<MyMsg<T>, Error>")]
pub struct MyMsg<T> {
    pub data: T,
}
1

There are 1 best solutions below

1
Finomnis On BEST ANSWER

I assume you use anyhow, because otherwise Result<..., Error> wouldn't make much sense. (as Error is a trait, not a type)

Then, I don't understand your problem, it just works:

use actix_derive::Message;
use anyhow::Error;

#[derive(Message)]
#[rtype(result = "Result<MyMsg<T>, Error>")]
pub struct MyMsg<T: 'static> {
    pub data: T,
}

If you expand that with cargo expand, you can see that you get:

#![feature(prelude_import)]
#[prelude_import]
use std::prelude::rust_2021::*;
#[macro_use]
extern crate std;
use actix_derive::Message;
use anyhow::Error;
#[rtype(result = "Result<MyMsg<T>, Error>")]
pub struct MyMsg<T: 'static> {
    pub data: T,
}
impl<T: 'static> ::actix::Message for MyMsg<T> {
    type Result = Result<MyMsg<T>, Error>;
}