[Solved] Help understanding how to annotate lifetime for generic trait type trait bound

Hi folks!

I'm unsure how to annotate the lifetime of the ParseFrom<&str> trait bound in the test function below. I would like to express that the lifetime of the input is independent of the lifetime of the return type.

Also, much more interested in furthering my understanding of Rust here, so if this is not possible, why exactly?

-L

	struct ParserErr(pub String);

	trait ParseFrom<I> : Sized {
		fn parse_from(from: I) -> Result<Self,ParserErr>;
	}
	/*
	error[E0637]: `&` without an explicit lifetime name cannot be used here
	  --> src/main.rs:19:21
	   |
	19 | fn test<T:ParseFrom<&str>>(from: String) -> Result<T,ParserErr> {
	   |                     ^ explicit lifetime name needed here
	*/
	fn test<T:ParseFrom<&str>>(from: String) -> Result<T,ParserErr> {
		T::parse_from(from.as_ref())    
	}

	fn main() {
	}

Playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=e2dd017c4e4ed3072768568f0857c541

To "invent" a temporary lifetime that's not related to the function or the object, you use for<'a> syntax.

fn test<T: for<'a> ParseFrom<&'a str>>(from: String) -> Result<T,ParserErr> {
1 Like

Wow thanks kornel! I would have never figured that out.

Do you have a link where I can read more about this feature?

https://doc.rust-lang.org/nomicon/hrtb.html

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.