Does exists a way to pass generic arguments at runtime?

51 Views Asked by At

I mean, I have a function that receives a serialized argument, then internally de-serializes it into T and calls to another function with T argument de-serialized.

Something like this.

// Args Struct: T target for de-serialize argument
struct InnerArgs {
    //...
    //fields
    //...
}

// outer function
fn outer(args: &[u8]) -> Result<(), ()> {
    // this is the line for de-serialize
    let args = serde::deserialized::<InnerArgs>(args).unwrap();

    inner(args)
}

// inner function
fn inner(args: InnerArgs) -> Result<(), ()> {
    ///whatever thing
}

I'm generating all this stuff with macros from info about a function signature from a trait.

This works well, but...

I want to support generic types for Args Struct like this:

// T target but with generics
struct InnerArgs<U> { 
    t: U
    //whatever fields
    //...
}

// outer function but I can't change the signature :(
fn outer(args: &[u8]) -> Result<(), ()> {
    // this is the line for deserialize
    let args = serde::deserialized::<InnerArgs>(args).unwrap();

    inner(args)
}

// inner function now with U generic
fn inner<U>(args: InnerArgs<U>) -> Result<(), ()> {
    ///whatever thing
}

But I can't change the signature for the outer function, it means I have no knowledge about the generics when I'm inside the function for de-serialize argument.

But I can play with the structure of the arguments, because is a "Request" and I can for example modify it to de-serialize it in several steps.

And here is my doubt - Exist any way to calculate the generic parameter and pass it at runtime?

Is it possible to pass some kind of meta-information about the generic maybe with syn or something else to achieve this?

0

There are 0 best solutions below