A compilation of concepts I want to remember...

Navigation
 » Home
 » About Me
 » Github

Rust borrowing #2

14 Jan 2017 » rust

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

  1. Ownership (Covered in the previous post)

  2. References and Borrowing

  3. Lifetimes

In this post will summarize my general understanding of borrowing.

tl;dr: The concept of borrowing, prevents iterator invalidation, and use after free, helping to create a safer environment. If you want to mutate a passed variable, need to utilize a mutable reference.

Point #1:

Essentially, under references and borrowing, a resource is lent by the owner and “borrowed” by the function.

For example, consider the below as example given:

fn foo(v1: &Vec<i32>, v2: &Vec<i32>) -> i32 {
    
    42
}

let v1 = vec![1, 2, 3];     //v1 has ownership
let v2 = vec![1, 3, 3];     //v2 has ownership

let answer = foo(&v1, &v2); //ownership is lent to foo

//foo consumes and returns the borrowed resource.

println!("{}",v1[0]);       //This is ok! as owenership has been returned back to v1

Point #2

References are immutable. Thus a variable passed by reference, lets say v1 in the above case, can not be amended within foo. Will give an error.

fn foo(v: &Vec<i32>) {
    v.push(5);      //illegal operation, v is borrowed, cant mutate.
}

let v = vec![];     //v has ownership

foo(&v);            //foo borrows

Point #3

If we want to mutate a borrowed variable, need to use a “mutable reference”. The example given is as follows:

let mut x = 5;      //x has ownership and x is mutable.
{
    let y = &mut x; //y borrows a mutable reference.
    *y += 1;        //y can now mutate x, but needs to use '*' operator
}
println!("{}", x);  //x returns 6 
    

The rules defined in the documentation:

First, any borow must last for a scope no greater than that of the owner. Second, you may have one or the other of these two kinds of borrows, but not both at the same time. 1) one or more references (&T) to a resource, 2) exactly one mutable reference (&mut T).