Rustlings: Live!

Goals:

Share knowledge

Ask Questions

Pair

Grow

Social Rules

https://www.recurse.com/manual

Have Fun!

Rust's Ownership Model

Memory Management

Techniques of memory Management Languages
Garbage Collection Java, .Net, Ruby, Python, JS
Explicit Memory Allocation C, C++
Ownership Rust 🦀

Memory Management

What is memory safety?

Memory safety is the property of a program where memory pointers used always point to valid memory, i.e. allocated and of the correct type/size. Memory safety is a correctness issue—a memory unsafe program may crash or produce nondeterministic output depending on the bug.

-- Will Crichton

dangling pointers:

Pointers that point to invalid data

double frees:

Trying to free the same memory location twice

Memory Management

Heap

Stack

Stacks

Last In

First Out

Fixed size

Heaps

Any arbitrary size

Allocate space

Identifiableaddress

Stack vs Heap

Data Types
Stack booleans, characters, integers
Heap strings, lists, arrays and other collections

All values in Rust are stack allocated by default. Values can be boxed (allocated on the heap) by creating a Box<T>

Rules of Ownership

  • 1 variable  =>  1 owner

  • 1 Owner! 

  • Variable is only valid when owner is in scope

Variable Scope

"Moving" Ownership

name value
pointer
len 5
capacity 5
name value
pointer
len 5
capacity 5
index value
0 h
1 e
2 l
3 l
4 o
index value
0 h
1 e
2 l
3 l
4 o

Not how rust works

S1

S2

name value
pointer
len 5
capacity 5
name value
pointer
len 5
capacity 5
index value
0 h
1 e
2 l
3 l
4 o

How rust works

S1

S2

name value
pointer
len 5
capacity 5
name value
pointer
len 5
capacity 5
index value
0 h
1 e
2 l
3 l
4 o

How rust works

S1

S2

let s1 = String::from("hello");
let s2 = s1; 

println!("{}", s1);

Ownership: "shallow copy"

Ownership in Functions

Ownership in Functions

Rules of Ownership

  • Begins with Assignment

  • Ends with scope

  • Moves with reassignment

References and Borrowing

References and Borrowing

Mutable References

Let's Pair!

Rustlings

https://github.com/rust-lang/rustlings

Rustlings

Move Semantics

$ rustlings run move_semantics1 
$ rustlings hint move_semantics1 
Complete Exercises 
1, 2, 3, 4

Rustlings: Live!

By shortdiv

Rustlings: Live!

  • 621