A Small Introduction to Lifetimes

This web page will introduce the reader to some basic ideas about Rust lifetimes through a set of exercises.

The Problem

First of all, consider a structure S that contains only one integer, and write a function larger that receives as parameters two values of type S and returns the structure containing the larger integer. This is a possible solution to the exercize

Now, notice that in the previous solution the ownership of the two values is moved away from s1 and s2... So, these two variables cannot be used after calling larger().

A Non-Working Solution

So, let's try to borrow the two values... This still does not build! Why? Right, returning *v1 or *v2 will try to move a borrowed value (which cannot be done).

Yet another try: let's return a reference... Still does not build???

The Real Solution (tm)

After you understood the issue (hint: the rustc error provides a very useful "rustc --explain ..." suggestion), you know how to fix the issue. It is actually pretty simple!