Rust is a systems programming language that was first initiated in 2006 and reached 1.0 in 2015. It is used by Mozilla in Firefox and focuses on memory safety without garbage collection through features like ownership and borrowing. The document provides an introduction to Rust and covers topics like variables, functions, primitive types, if/loop control structures, ownership, references, and encourages readers to explore further topics in the Rust Book and Rust by Example.
2. Brief Introduction
First initiated by Graydon Hoare in 2006 as a part-time
project
Adopted by Mozilla Foundation in ~2009
Reached 1.0 in May 2015
Currently on 1.12 (stable), 1.13 (beta) and 1.14(nightly)
Firefox is already shipping with Rust code since version 48
14. Primitive Types
Booleans
let x = true;
let y: bool = false;
Char
let x = 'x';
let two_hearts = ' '
Numeric
let x = 42; // x has type i32
let y = 1.0; // y has type f64
17. IF
let x = 5;
if x == 5 {
println!("x is five!");
} else {
println!("x is not five :(");
}
let x = 5;
if x == 5 {
println!("x is five!");
} else if x == 6 {
println!("x is six!");
} else {
println!("x is not five or six :(");
}
18. IF
let x = 5;
let y = if x == 5 { 10 } else { 15 }; // y: i32
19. Loops
loop {
println!("Loop forever!");
}
let mut x = 5; // mut x: i32
let mut done = false; // mut done: bool
while !done {
x += x - 3;
println!("{}", x);
if x % 5 == 0 {
done = true;
}
}
20. Loops
Rust does not have the “C-style” for loop on purpose.
Manually controlling each element of the loop is complicated
and error prone, even for experienced C developers.
for x in 0..10 {
println!("{}", x); // x: i32
}
for (index, value) in (5..10).enumerate() {
//When you need to keep track of how many times you already looped
println!("index = {} and value = {}", index, value);
}
21. Ownership
Variable bindings have a property in Rust: they ‘have
ownership’ of what they’re bound to. This means that when a
binding goes out of scope, Rust will free the bound resources.
For example:
let v = vec![1, 2, 3];
let v2 = v;
println!("v[0] is: {}", v[0]);//error: use of moved value: `v`
22. Ownership
fn take(v: Vec<i32>) {
// what happens here isn’t important.
}
let v = vec![1, 2, 3];
take(v);
println!("v[0] is: {}", v[0]);//same error, used of moved value `v`</i32>
24. Ownership
borrowing
fn foo(v1: Vec<i32>, v2: Vec<i32>) -> (Vec<i32>, Vec<i32>, i32) {
// do stuff with v1 and v2
// hand back ownership, and the result of our function
(v1, v2, 42)
}
let v1 = vec![1, 2, 3];
let v2 = vec![1, 2, 3];
let (v1, v2, answer) = foo(v1, v2);</i32></i32></i32></i32>
25. Ownership
References
n foo(v1: &Vec<i32>, v2: &Vec<i32>) -> i32 {
// do stuff with v1 and v2
// return the answer
42
}
let v1 = vec![1, 2, 3];
let v2 = vec![1, 2, 3];
let answer = foo(&v1, &v2);
// we can use v1 and v2 here!</i32></i32>