Type arguments with block-level lifetime

26 Views Asked by At

I have a fuction I want to supply with generic type arguments. However, in this case they require a specific lifetime (because of serde::de::Deserialize<'de>).

The type arguments are to be passed to a function, here called run within the function myfunction. The argument &data is only alive for the lifetime of the Ok(data) block, which is in conflict of the lifetime 'b of the generic type argument of myfunction.

If concrete types are supplied, this works right away, but as generic types are bound to the lifetime I'm not sure how to work around this. Is there a way to specify the lifetime of the Ok(data) block or another way to supply the type arguments? Otherwise I'd have to have a myfunction variant for every type combination I need, which is possible, but not optimal or elegant.

I've put code with the functions that make this example run on the rust playground.

//the function in question
fn myfunction<'b, T1, T2>(req: &'b [u8]) -> Result<(), ()>
where
    T2: TaskResult<'b>,
    T1: TaskInfo<'b, T2>,
{
    match extract_body(req) {
        Ok(data) => {
            // if concrete types are supplied, it works.
            //let t = run::<Test1, Test2>(&data);
            // as the generic types are bound to the lifetime 'b,
            // which is longer than data would live
            let t = run::<T1, T2>(&data);
            //do something with t
            Ok(())
        }
        Err(_) => panic!("error"),
    }
}

//can't be changed, as it is an abbreviated function of a crate I'm using.
fn extract_body(req: &[u8]) -> Result<bytes::Bytes, ()> {
    Ok(bytes::Bytes::from(req))
}

I hope there is a workaround for this.

0

There are 0 best solutions below