1

I have a trait that's defined like this:

use serde::{Deserialize, Serialize};

trait MyTrait {    
     type InputDoc: Deserialize; //Error: missing lifetime specifier: expected lifetime parameter
     type OutputDoc: Serialize;

     fn create() -> Self;
     fn process(& self, doc: &Self::InputDoc) -> Self::OutputDoc;  
}

I want to use the trait like this:

fn run<M: MyTrait>() -> () {
    let mytrait = M::create();

    let data = ...load some string from somewhere ...;
    let doc: serde_json::Result<M::InputDoc> = serde_json::from_str(data);
    let result = mytrait.process(&doc);
}

The problem looks similar to this question, but I could not get it to work with the proposed solution. I actually don't get why the lifetime is needed at all, which makes it even harder to figure out the solution. Can somebody explain how to specify a lifetime, that allows my example to work?

Achim
  • 15,415
  • 15
  • 80
  • 144
  • 2
    Does this answer your question? [Lifetime error when creating a function that returns a value implementing serde::Deserialize](https://stackoverflow.com/questions/43554679/lifetime-error-when-creating-a-function-that-returns-a-value-implementing-serde/43564347#43564347) – Sven Marnach Feb 18 '20 at 10:47
  • 2
    In short, you can use `DeserializeOwned`, which is effectively a shorthand for the HRTB `for<'de> Deserialize<'de>`. – Sven Marnach Feb 18 '20 at 10:48
  • This is a pretty common issue; see also [Lifetimes when Deserializing JSON within a FromForm](https://stackoverflow.com/questions/45783315/lifetimes-when-deserializing-json-within-a-fromform) – trent Feb 18 '20 at 12:09

0 Answers0