0

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.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
rudib
  • 227
  • 1
  • 10
  • I believe your question is answered by the answers of [How to specify lifetime bounds for a closure involving references to intermediate local variables?](https://stackoverflow.com/q/49341520/155423) and [How does for<> syntax differ from a regular lifetime bound?](https://stackoverflow.com/q/35592750/155423). If you disagree, please [edit] your question to explain the differences. Otherwise, we can mark this question as already answered. – Shepmaster Nov 18 '18 at 13:39
  • 2
    See also [Lifetime error when creating a function that returns a value implementing serde::Deserialize](https://stackoverflow.com/q/43554679/155423) – Shepmaster Nov 18 '18 at 13:41
  • Thanks a lot, I'll see if it works. – rudib Nov 18 '18 at 13:45
  • 1
    @Shepmaster Thank you, `serde::de::DeserializeOwned` seems to be the perfect solution. Didn't find even this after after looking for it for days! – rudib Nov 18 '18 at 13:53

0 Answers0