How to create a trait based on a trait with implicit lifetime?

We assume there is an external trait

trait ParseStr<'a>{
    fn parse_str(input:&'a str)->Self;
}

Now I want to define a trait like this, so that I could implement join_and_parse which is a function that could join a series of string slices and parse their combination, surely it was just an example.

trait MyParseStr:ParseStr<'_>{}
    
fn join_and_parse<T:MyParseStr>(arr:&[&str])->T{
    let s=arr.join("");
    T::parse_str(&s)
}

But the compliler disagreed with me to do so.

error[E0106]: missing lifetime specifier
 --> src/main.rs:7:31
  |
7 |     trait MyParseStr:ParseStr<'_>{}
  |                               ^^ expected named lifetime parameter
  |
help: consider introducing a named lifetime parameter
  |
7 |     trait MyParseStr<'a>:ParseStr<'a>{}
  |                     ++++          ~~

But obviously, if I modified my code as the compiler suggested, the reference of s in the function will be considered to be brought out of the function, so it's not the correct workaround. How can I solve this problem or how to implement this function?

Higher ranked trait bounds will help

MyParseStr: for<'a> ParseStr<'a>

Note that ParseStr appears to be structured in a way that it can support implementations from borrowing types that don't create any owned copies of the underlying str data; e. g. an implementation ParseStr<'a> for &'a str or perhaps ParseStr<'a> for &'b str where 'a: 'b. These kinds of types won't meet this kind of HRTB supertrait bound then. But they can't work anyways, because your code creates a String temporarily in a local variable, shows it to T::parse_str and then drops it, so the parsed T can actually not keep any references to the str around.

2 Likes

Do you want for<'a> ParseStr<'a> by any chance? Playground

Thanks, that's what I want. I don't know the "higher ranked trait bounds" grammar you mentioned.

For more information, the Ownership chapter of the Rustonomicon is a good read introducing a few advanced concepts including HRTBs

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.