Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

This is determined by lifetime elision [1]. Specifically (quoting):

- Each elided lifetime in the parameters becomes a distinct lifetime parameter.

- If there is exactly one lifetime used in the parameters (elided or not), that lifetime is assigned to all elided output lifetimes.

So, Since the signature has one `&str` as a parameter, the lifetime is assigned to the output lifetime also per these rules.

[1]: https://doc.rust-lang.org/reference/lifetime-elision.html

(Edited to improve formatting)



Ahh. So if I added a second parameter it would require the explicit lifetime? That may be what I was doing before that made me think I needed to be explicit all the time.


Yes - if there are two references as parameters, there is no way for the compiler to decide which the output reference may be borrowed from - and so which lifetime to assign the output, so it must be explicitly indicated by the programmer.

There are a few a few example cases in the doc linked about that walk through the conditions it's necessary to add explicit lifetime annotation.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: