A compilation of concepts I want to remember...

Navigation
 » Home
 » About Me
 » Github

Rust ownership #1

12 Jan 2017 » rust

I will follow the documentation at rust-lang.org to get a better grip on ownership. The tutorial breaks down the concept in three chunks:

  1. Ownership

  2. References and Borrowing

  3. Lifetimes

In this post will summarize my general understanding of ownership.

tl;dr: Keep in mind the ownership concept when reassigning variables with existing bindings. If not a primitive, an error will occur at compile time.

Point #1:

Basically that variable bindings have ownership of what the variable is bound to. The example given is that:

fn foo() {
    let v = vec![1,2,3];
}

Ok, to have “ownership” means that v basically owns vec![1,2,3]. Thus if we decide set a new variable, y = v, then v no longer has ownership, and will result in a compile time error. This addresses the idea that Rust gaurantees that bindings to resources are unique.

This is not allowed:

fn foo() {
    let v = vec![1,2,3];
    y = v;
    println!("{}", v[0]);
}

The phrase used is “move”, as in the error will be related to the attempt to accessing, the use of the “moved” value v.

Point #2:

The trait, Copy, is introduced, where a trait is feature that adds incremental behavior.

Basic concept is that if its a primitive type that is bound, then the Copy trait comes in to play and we can reassign ownership and still address the original the original variable.

fn foo() {
    let v = 5;
    y = v;
    println!("{}", v);
}

Ok, this is fine now and will compile as 5 is a primitive. Essentially the Copy trait invokes a deep copy, and y does not reference the object pointed to by v.