Menu

1 / 2

[Rust Guide] 10.7. Input and Output Lifetimes and the 3 Rules

DEV Community·SomeB1oody·7 months ago
#16VCjc3v
#rust#programming#learning#software#lifetime
Reading 0:00
15s threshold

If you find this helpful, please like, bookmark, and follow. To keep learning along, follow this series.

10.7.1 A Deeper Understanding of Lifetimes

1. The Way Lifetime Parameters Are Specified Depends on What the Function Does

Take the code from the previous article as an example:

fn longest < 'a > ( x : & 'a str , y : & 'a str ) -> & 'a str { if x .len () > y .len () { x } else { y } }

Enter fullscreen mode

Exit fullscreen mode

The reason this function signature is written this way is that it is not known whether the return value will be x or y . If I modify the code so that the return value is fixed as x , then there is no need to give y an explicit lifetime:

fn longest < 'a > ( x : & 'a str , y : & str ) -> & 'a str { x }

Enter fullscreen mode

Exit fullscreen mode

So this function signature does not constrain y ’s lifetime.

2.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.