A compilation of concepts I want to remember...

Navigation
 » Home
 » About Me
 » Github

Rust lifetime #3

20 Jan 2017 » rust

Following on in my dive into the concept of ownership in Rust, will assess the idea of lifetimes. I will follow the documentation at rust-lang.org. The tutorial breaks down the concept in three chunks:

  1. Ownership (Covered in a previous post)

  2. References and Borrowing (Covered in a previous post)

  3. Lifetimes

In this post will summarize my general understanding of lifetimes.

tl;dr: the concept of lifetimes seems quiet complex, but makes “lifetimes” of values transparent and promotes safer programming.

Point #1: “use after free” prevention

The documentation provides a rather intuitive break down of an example of what the concept of lifetimes is attempting to prevent.

  1. I acquires a handle to some kind of resource.

  2. I lend a reference to the resource to you.

  3. I free the resource, as I am done with the resource, and decide to deallocate.

  4. You decide to use the resource.

This would cause an error. The reference you have been lent is now pointing at an invalid resource. The ‘use after free’ concept should be familiar and applies to this scenario.

let you;                    //introduce you

{
    let me = "resource";    //introduce scope value, me
    you = &me;              //me lends the reference to "resource" to you
}

println!(you);              //you is still referencing resource of me

The above would fail, as a you is referecing a resource that has gone out of scope. The rust compiler is able to catch this as a result of having visibility on the “lifetimes” of different values.

Point #2: syntax

Some syntax to keep in mind. Rust allows functions to have generic parameters placed between <>:

fn foo<'a>(...)             //foo has one lifetime, 'a
fn bar<'a, b'>(...)         //bar has two lifetimes, in the case we had two reference
                            //parameters with different lifetimes. 

fn foo<'a>(x: &'a i32)      //a reference to an i32, with a lifetime 'a
fn foo<'a>(x: &'a mut i32)  //a mutable reference to an i32, with a lifetime 'a


struct Foo<'a> {            //when dealing with structs, need to ensure
    x:  &'a i32,            //that any reference to Foo doesnt outlive a
}                           //reference to the i32 the struct it contains
    

Point #3: ‘static lifetime

Static lifetime is a special type of lifetime that has a lifetime over the entire program.

static FOO: i32 = 5;            //adds an i32 to the data segment of the binary.
let x: &'static i32 = &FOO;     //x refers to the i32