Git repository: https://github.com/caveofprogramming/rust/
Functions and Lifetimes
In rust, the following program doesn’t compile unless we move the println!()
inside the brackets
All references have a lifetime, and in this case, the variable y
is dropped at the closing bracket, meaning the reference x
doesn’t “live long enough” to be printed outside the brackets.
Lifetime parameters are generic parameters and begin with an apostrophe. Usually single lower-case letters are used to name them.
The most common function of them is to connect the lifetime of references returned from functions to the lifetimes of arguments upon which they depend.
The following program, which just returns its argument, compiles fine.
The generic parameter ‘a
is a lifetime annotation. It specifies that the returned reference lives as long as the s parameter.
In this case, the program also compiles without the ‘a
lifetime specification, because this situation is simple enough for the Rust compiler to not require it.
In the following program, the lifetime annotations are necessary for the longest function to compile.
Here’s my understanding of this program: the generic parameter ‘a is inferred from the arguments passed to the function. ‘a
will end up specifying that the lifetime of the returned reference is as long as the shortest lifetime of any of the input parameter references.
Struct Lifetime Parameters
Structs can also contain references, but then you also need to specify lifetime parameters.
Starfields
In the video I also demonstrate that you can create an animated starfield program using Microsoft Hotspot, and with a few slight tweaks no warnings even appear when you compile it!