Reputation: 33
I have a trait that I use as an interface to Rails' ActiveJob; I want my Rust backend to fire jobs to be processed by a Rails API:
trait BackgroundJob {
type Args: Serialize;
const QUEUE: &'static str;
const CLASS: JobClass;
fn payload(self) -> Self::Args;
}
An example implementation of the trait:
impl BackgroundJob for MyJob {
type Args = (String,);
const QUEUE: &'static str = "my_queue";
const CLASS: JobClass = JobClass::Job1;
fn payload(self) -> Self::Args {
(self.payload,)
}
}
In my application the code is a little bit more complex (specifically, I have an Actix actor instead of the generic function over BackgroundJob
) but the idea is the same.
This code works fine but I have to make sure that all the implementations of BackgroundJob
will have as the Args
type parameter something that will serialize to a JSON array (to work with active job).
What I would like to do is to have a compile-time guarantee that Args
will serialize to an array. Is that possible?
I tried to work around with SerializeTuple
and SerializeSeq
traits from Serde but without success.
Upvotes: 3
Views: 218
Reputation: 430981
I'm pretty sure the answer is "no, there's nothing native to Serde to do this". There's no trait corresponding to this specific need.
You could make your own marker trait and require that it be present, but it wouldn't be automatically implemented by anything; you'd have to manually implement it for any valid type. I'm guessing it wouldn't be what you want:
trait SerializeToJsonArray {}
impl<T> SerializeToJsonArray for Vec<T> {}
impl<T> SerializeToJsonArray for [T] {}
impl<A> SerializeToJsonArray for (A, ) {}
impl<A, B> SerializeToJsonArray for (A, B, ) {}
impl<A, B, C> SerializeToJsonArray for (A, B, C, ) {}
// etc.
trait BackgroundJob {
type Args: Serialize + SerializeToJsonArray;
}
This is also trivially breakable — you can easily implement SerializeToJsonArray
for types that don't serialize to an array. Likewise, Serde doesn't know about this trait and you'll still need to handle non-arrays at serialization time.
Upvotes: 1