Genericizing struct/impl results in lifetime error

I'm trying to write a Serde deserializer, and I'm running into an issue where I can't seem to genericize a function. The longer test case and compilation error is here:

Curiously, replacing line 119 with seed.deserialize(IntDeserializer::from_input(self.input)).map(Some), referencing the concrete type, compiles just fine.

@udoprog in Discord helped construct a more minimal test case:

trait Build<'out> {
    fn build(data: &'out mut ()) -> Self;
}

#[derive(Debug)]
struct Foo<'out>(&'out mut ());

impl<'out> Build<'out> for Foo<'out> {
    fn build(data: &'out mut ()) -> Self {
        Self(data)
    }
}

trait Builder<'out> {
    // This trait cannot be modified
    fn builder<T: Build<'out>>(&mut self);
}

struct Bar<'out>(&'out mut ());

impl<'out> Builder<'out> for Bar<'out> {
    fn builder<T: Build<'out>>(&mut self) {
        // Works:
        let a = Foo::build(self.0);
        // Doesn't work:
        let b = T::build(self.0);
    }
}

I notice that the reason why the concrete type works is because the concrete type accepts any lifetime, which includes the local anonymous lifetime. How do I express this in the generic type of T such that it is able to do the same? Or is it not possible to genericize such a struct/impl?

It is unusual to try and implement Deserializer directly for a non-reference type if you are deserializing from a slice. You should rather implement it for &mut TheDeserializerType, and when you need to impose trait bounds on it, use HRTB: where for<'a> &'a mut D: Deserializer<'de>. (Playground)

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.