Notes and Guides

Rust - Guide

For projects check Rust Book Project

Documentation

There is an offline version of the documentation

rustup doc

Installation

Download the rust installer from Rust Download Page.

Check the environment variables Path and make sure that the folder C:\Users\Crow\.cargo\bin is in there.

In the case that you already have rust installed, update it with the command:

rustup update

To uninstall run

rustup self uninstall

To check if it was installed correctly:

rustc --version

You will get something like this:

rustc 1.41.0 (5e1a79984 2020-01-27)

Hello, World

  1. Create a folder for the new project hello_world.
  2. Create a file named main.rs
  3. Write the following:

    fn main() {
        println!("Hello, world!");
    }
    
  4. Compile the program with

    rustc main.rs
    
  5. Run the program with

    .\main.exe
    

Output:

Hello, World!

Cargo

Check Installation

Check if you have cargo installed:

cargo --version

If you have, you will see something like this:

cargo 1.41.0 (626f0f40e 2019-12-03)

New Project

Create a new project with:

cargo new <project_name>

By default, it creates a --bin project (binary). To create a library project use --lib.

  • Library vs Binary

    A common pattern, even for binary-only crates, is to declare a "library" providing the majority of functionality, and then have main.rs just implement argument parsing and use that library.

    This allows for integration tests written against the library, which might otherwise be hard to do with only main.rs.

  • TOML File

    This file indicates the information about the developer, the name of the app and its version.

    It also indicates the dependencies.

    [package]
    name = "hello_cargo"
    version = "0.1.0"
    authors = ["Author Name <user@hotmail.com>"]
    edition = "2018"
    
    # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
    
    [dependencies]
    

Build

To build the project, run:

cargo build

For a release version:

cargo build --release

Run

To run the project, run:

cargo run

For a release version:

cargo run --release

Check - Run the compiler without compiling

This is useful when compiling takes too long and you want to check if there are compile errors.

cargo check

For a release version:

cargo check --release

Update Crates

cargo uptate

Crates and Project Documentation

Open the documentation for all the crates in your project with:

cargo doc --open

Release Optimization

To optimize the release build for your own processor, add this settings to the cargo.toml file:

[profile.release]
# Link-Time optimization
lto = "fat"
# Increase compile time and in return,
# optimize all crates one by one
codegen-units = 1
# target your cpu specifically
target-cpu = "native"
# some libraries don't support this
#panic = "abort"

With a stupid test of doing 1.000.000 iterations and generating 150 fibonacci sequences it reduce the execution time from 382 milliseconds to 378 milliseconds.

Variables

By default variables are immutable - they cannot be changed after the assignment.

fn main() {
    let x = 5;
    x = 2;
}
 --> src\main.rs:15:5
  |
2 |     let x = 5;
  |         -
  |         |
  |         first assignment to `x`
  |         help: make this binding mutable: `mut x`
3 |     x = 2;
  |     ^^^^^ cannot assign twice to immutable variable

Mutable Variables

let x = 5; // immutable
let mut y = 5; // mutable
println!("X: {}, Y: {}", x, y); // X: 5, Y: 5
y = x + 5;
println!("New Y: {}", y); // New Y: 10
y += 5;
println!("New Y 2: {}", y); // New Y 2: 15

Special Variables

  • Unused variables

    Variables that start with an _ wont have a warning of being unused. You use this variables when you're developing and don't want to be warned about a variable being unused.

    // we may use `_x` eventually, but our code is a work-in-progress
    // and we just wanted to get rid of a compiler warning for now.
    let _x = 42;
    
  • Throw away variables

    When you don't want to store a value in a variable, but have to put something because it is returned from a function, use _ as name.

    // this calls `get_thing` but throws away its result
    let _ = get_thing();
    
    // destructuring
    let (some_char, some_int) = ('a', 17);
    

Statements in variables

let x = {
    let y = 1; // first statement
    let z = 2; // second statement
    y + z // this is the *tail* - what the whole block will evaluate to
};

Constants

const MAX_HITPOINTS: u32 = 100_000;

fn main() {

    let mut x: u32 = 5;
    println!("X = {}", x);

    x = 6;

    println!("New X = {}", x);

    println!("Max Hitpoints = {}", MAX_HITPOINTS);

    x += MAX_HITPOINTS;

    println!("New x= {}", x);

}

Types

So how do you know which type of integer to use? If you're unsure, Rust's defaults are generally good choices, and integer types default to i32: this type is generally the fastest, even on 64-bit systems. The primary situation in which you'd use isize or usize is when indexing some sort of collection.

  • Integers
    Length Signed Unsigned
    8-bit i8 u8
    16-bit i16 u16
    32-bit i32 u32
    64-bit i64 u64
    128-bit i128 u128
    arch isize usize

    Each signed variant can store numbers from:

    \[(-2^{n-1}) \to (2^{n-1} - 1)\]

    for example an i8 can store numbers from \((-2^7)\) to \((2^7 - 1)\), which equals from \(-128\) to \(127\)

    Each unsigned variant can store numbers from:

    \[0 \to (2^{n} - 1)\]

    for example a u8 can store numbers from \(0\) to \(2^8 - 1\) which to \(255\).

  • Number Literals

    All number literals, except for byte literal, allow a type suffix and a _ as a visual separator, such as 1_000.

    Number literals Example
    Decimal 98_222
    Hex 0xff
    Octal 0o77
    Binary 0b1111_0000
    Byte (u8 only) b'A'
  • Float

    The default type is f64 because on modern CPUs it's roughly the same speed as f32 but is capable of more precision.

    Precision length
    Single precision f32
    Double precision f64
  • Boolean
    fn main() {
        let t = true;
    
        let f: bool = false; // with explicit type annotation
    }
    
  • Character

    The char literal is specified with single quotes 'c'.

    fn main() {
        let c = 'z';
        let z = 'ℤ';
        let heart_eyed_cat = '😻';
    }
    
  • Tuple
    fn main() {
        let tup: (i32, f64, u8) = (500, 6.4, 1);
        let (x, y, z) = tup;
        println!("The value of y is: {}", y);
    
        let five_hundred = tup.0;
    
        let six_point_four = tup.1;
    
        let one = tup.2;
    }
    
  • Array

    Arrays are useful when you want your data allocated on the stack rather than the heap, or when you want to ensure you always have a fixed number of elements, it cannot grow or shrink.

    A vector is a similar collection type provided by the standard library that is allowed to grow or shrink in size. If you're unsure whether to use an array or a vector, you should probably use a vector.

    fn main() {
        let a = [1, 2, 3, 4, 5];
    
        let first = a[0];
        let second = a[1];
    
        let months = ["January", "February", "March", "April", "May", "June", "July",
                      "August", "September", "October", "November", "December"];
    
        // [type; length]
        let b: [i32; 5] = [1, 2, 3, 4, 5];
    }
    

Numeric Operations

fn main() {
    // addition
    let sum = 5 + 10;

    // subtraction
    let difference = 95.5 - 4.3;

    // multiplication
    let product = 4 * 30;

    // division
    let quotient = 56.7 / 32.2;

    // remainder
    let remainder = 43 % 5;
}

Functions

fn greet() {
    println!("Hi there!");
}

Arguments

fn main() {
    another_function(5);
}

fn another_function(x: i32) {
    println!("The value of x is: {}", x);
}

Multiple parameters:

fn main() {
    another_function(5, 6);
}

fn another_function(x: i32, y: i32) {
    println!("The value of x is: {}", x);
    println!("The value of y is: {}", y);
}

Statements and Expressions

Statements are instructions that perform some action and do not return a value. Expressions evaluate to a resulting value.

fn main() {
    let x = 5;

    let y = {
        let x = 3; // Statement
        x + 1 // Expression, note the lack of `;`
        // Evaluates to `4` -> (3 + 1)
    };

    println!("The value of y is: {}", y);
}

Return Values

//        \/ the return value
fn five() -> i32 {
    5
}

fn main() {
    let x = five();

    println!("The value of x is: {}", x);
}

Structs

Define

struct Vec2 {
    x: f64, // 64-bit floating point, aka "double precision"
    y: f64,
}

Initialize

let v1 = Vec2 { x: 1.0, y: 3.0 };
let v2 = Vec2 { y: 2.0, x: 4.0 };
// the order does not matter, only the names do
  • Shortcut

    Create a Vec2 object with x = 14.0 and all the other fields with the values from the v2 variable.

    let v3 = Vec2 {
        x: 14.0,
        ..v2
    };
    

    Create a Vec2 object with all the fields being equal to the v3 variable.

    let v4 = Vec2 { ..v3 };
    

Destruct

let v = Vec2 { x: 3.0, y: 6.0 };
let Vec2 { x, y } = v;
// `x` is now 3.0, `y` is now `6.0`
let Vec2 { x, .. } = v;
// this throws away `v.y`

Impl

Define methods for you structs.

struct Number {
    odd: bool,
    value: i32,
}

impl Number {
    fn is_strictly_positive(self) -> bool {
        self.value > 0
    }
}

fn main() {
    let minus_two = Number {
        odd: false,
        value: -2,
    };
    println!("positive? {}", minus_two.is_strictly_positive());
    // this prints "positive? false"
}

Traits

Traits are something that you can implement for types. For example, you want to implement a function that can be used in your struct and add it to another type.

Traits can also say what can be done with a type. For example, you create a struct and a variable let a = YourStruct...;. If you try to give that value to other variable let b = a and let c = a, the variable c will cause error because a no longer exists. This happens because your struct doesn't implement the Copy trait.

Example: create a trait called Signed that has a function that checks if self is negative. Apply this function to the Number struct and to i32 type.

trait Signed {
    fn is_strictly_negative(self) -> bool;
}

impl Signed for Number {
    fn is_strictly_negative(self) -> bool {
        self.value < 0
    }
}

fn main() {
    let n = Number { odd: false, value: -44 };
    println!("{}", n.is_strictly_negative()); // prints "true"
}
impl Signed for i32 {
    fn is_strictly_negative(self) -> bool {
        self < 0
    }
}

fn main() {
    let n: i32 = -44;
    println!("{}", n.is_strictly_negative()); // prints "true"
}

Foreign Traits

// the `Neg` trait is used to overload `-`, the
// unary minus operator.
impl std::ops::Neg for Number {
    type Output = Number;

    fn neg(self) -> Number {
        Number {
            value: -self.value,
            odd: self.odd,
        }
    }
}

fn main() {
    let n = Number { odd: true, value: 987 };
    let m = -n; // this is only possible because we implemented `Neg`
    println!("{}", m.value); // prints "-987"
}

Clone and Copy traits

Without implementing a Copy trait, you won't be able to this with your struct:

fn main() {
    let n = Number { odd: true, value: 51 };
    let m = n; // `n` is moved into `m`
    let o = n; // error: use of moved value: `n`
}
fn print_number(n: Number) {
    println!("{} number {}", if n.odd { "odd" } else { "even" }, n.value);
}

fn main() {
    let n = Number { odd: true, value: 51 };
    print_number(n); // `n` is moved
    print_number(n); // error: use of moved value: `n`
}

But it works with a reference:

fn print_number(n: &Number) {
    println!("{} number {}", if n.odd { "odd" } else { "even" }, n.value);
}

fn main() {
    let n = Number { odd: true, value: 51 };
    print_number(&n); // `n` is borrowed for the time of the call
    print_number(&n); // `n` is borrowed again
}

It also works with mutable variables:

fn invert(n: &mut Number) {
    n.value = -n.value;
}

fn print_number(n: &Number) {
    println!("{} number {}", if n.odd { "odd" } else { "even" }, n.value);
}

fn main() {
    // this time, `n` is mutable
    let mut n = Number { odd: true, value: 51 };
    print_number(&n);
    invert(&mut n); // `n is borrowed mutably - everything is explicit
    print_number(&n);
}

Implement the clone trait:

impl std::clone::Clone for Number {
    fn clone(&self) -> Self {
        Self { ..*self }
    }
}
fn main() {
    let n = Number { odd: true, value: 51 };
    let mut m = n.clone();
    m.value += 100;

    print_number(&n);
    print_number(&m);
}

There are equivalent:

let m = n.clone();

let m = std::clone::Clone::clone(&n);

Implement the Copy trait:

// Merker traits like `Copy` don't have any methods.
impl std::marker::Copy for Number {}

Now this works:

let n = Number { odd: true, value: 51 };
let m = n.clone();
let o = n.clone();

// and

let n = Number { odd: true, value: 51 };
let m = n; // `m` is a copy of `n`
let o = n; // same. `n` is neither moved nor borrowed.

Some traits are so common, they can be implemented automatically by using the derive attribute:

#[derive(Clone, Copy)]
struct Number {
    odd: bool,
    value: i32,
}

// this expands to `impl Clone for Number` and `impl Copy for Number` blocks.

Enums

Control Flow

If

  • Basic If

    This expression checks a condition for true or false. You can omit the else clause and the program will just skip it. The condition must be a bool. If the condition isn't a boolean you will get an error.

    fn main() {
        let number = 3;
    
        if number < 5 {
            println!("condition was true");
        } else {
            println!("condition was false");
        }
    }
    

    You can use it in a let statement, however the results of both arms must be of the same type:

    fn main() {
        let condition = true;
        let number = if condition {
            5
        } else {
            6
        };
    
        println!("The value of number is: {}", number);
    }
    
    • Chaining if clauses
      fn main() {
          let number = 6;
      
          if number % 4 == 0 {
              println!("number is divisible by 4");
          } else if number % 3 == 0 {
              println!("number is divisible by 3");
          } else if number % 2 == 0 {
              println!("number is divisible by 2");
          } else {
              println!("number is not divisible by 4, 3, or 2");
          }
      }
      
  • If let
    struct Number {
        odd: bool,
        value: i32,
    }
    
    fn main() {
        let one = Number { odd: true, value: 1 };
        let two = Number { odd: false, value: 2 };
        print_number(one);
        print_number(two);
    }
    
    fn print_number(n: Number) {
        if let Number { odd: true, value } = n {
            println!("Odd number: {}", value);
        } else if let Number { odd: false, value } = n {
            println!("Even number: {}", value);
        }
    }
    
    // this prints:
    // Odd number: 1
    // Even number: 2
    

Loops

  • Loop

    This will run forever until you explicitly tell it to stop:

    fn main() {
        loop {
            println!("again!");
        }
    }
    
    • Returning from loops
      fn main() {
          let mut counter = 0;
      
          let result = loop {
              counter += 1;
      
              if counter == 10 {
                  break counter * 2;
              }
          };
      
          assert_eq!(result, 20);
      }
      
  • While
    fn main() {
        let mut number = 3;
    
        while number != 0 {
            println!("{}!", number);
    
            number = number - 1;
        }
    
        println!("LIFTOFF!!!");
    }
    

    You can also use While to loop over a collection, but it is likely to make an error occur if you manually loop over the collection:

    fn main() {
        let a = [10, 20, 30, 40, 50];
        let mut index = 0;
    
        while index < 5 {
            println!("the value is: {}", a[index]);
    
            index = index + 1;
        }
    }
    
  • For
    fn main() {
        let a = [10, 20, 30, 40, 50];
    
        for element in a.iter() {
            println!("the value is: {}", element);
        }
    }
    

    Counting down:

    fn main() {
        // `rev` is used to reverse the range.
        for number in (1..4).rev() {
            println!("{}!", number);
        }
        println!("LIFTOFF!!!");
    }
    

Match

fn print_number(n: Number) {
    match n {
        Number { odd: true, value } => println!("Odd number: {}", value),
        Number { odd: false, value } => println!("Even number: {}", value),
    }
}

// this prints the same as before

It has to be exaustive. This means it has to reference all possible values.

fn print_number(n: Number) {
    match n {
        Number { value: 1, .. } => println!("One"),
        Number { value: 2, .. } => println!("Two"),
        Number { value, .. } => println!("{}", value),
        // if that last arm didn't exist, we would get a compile-time error
    }
}

The else clause can be _:

fn print_number(n: Number) {
    match n.value {
        1 => println!("One"),
        2 => println!("Two"),
        _ => println!("{}", n.value),
    }
}

Comments and Documentation

// So we’re doing something complicated here, long enough that we need
// multiple lines of comments to do it! Whew! Hopefully,
// this comment will explain what’s going on.

Comments with //! is used for module documentation and /// for function documentation.

//! This is the X module
//!
//! # What it does
//!
//! I don't know

fn main() {
    // This is a comment
    hello_world(); // Look! another comment.
}

/// Say hello to the whole world function
///
/// # How it works
///
/// ```rust
/// hello_world();
/// ```
pub fn hello_world() {
    println!("Hello, World!");
}

Print to console

To print a value to the console use the println!() function.

println!("Guess the number game!");

Placeholders

let x = 5;
println!("The value of x is: {}", x);
let x = 5;
let y = 6;
println!("The value of x is: {} and the value of y is:", x, y);

Error Handling

When a function returns Ok() or Err(), you can call .expect() to show the crash. It's advisable, however, to actually implement error handling.

Example:

io::stdin().read_line(&mut guess)
    .expect("Failed to read line");

Standard Library

The standard library std has the following modules:

  • io for input/output operations

Dependencies and Crates

Check for crates and theirs versions in Crates.io

Import crates with:

extern crate rand;
use rand::Rng;

To use multiple modules of a crate, use it like this:

// this works:
use std::cmp::min;
use std::cmp::max;

// this also works:
use std::cmp::{min, max};

// this also works!
use std::{cmp::min, cmp::max};

// this brings `min` and `max` in scope, and many other things
use std::cmp::*;

// Import the io module from std and import
// the Ordering module from the comp module
use std::{
    cmp::Ordering,
    io
};

Random Crate

Generate random numbers.

Dependencies:

[dependencies]

rand = "0.3.14"

Tests

Unit Tests

Unit tests work only for libraries.

An example of a unit test is:

/// Example sum function
///
/// # Objective
///
/// This function adds two numbers and returns the sum.
///
/// Also, it has an example section that functions as a test
/// for the function.
///
/// By using `#` before a statement in the code block, we can hide
/// the code.
///
/// # Examples
///
///```rust
///use guessing_game::sum_number;
///let x: i32 = 1;
///let y: i32 = 2;
///let sum = sum_number(x, y);
///# assert_eq!(sum, 3);
///```
pub fn sum_number(x: i32, y: i32) -> i32 {
    x + y + 1
}

Time Functions

use std::time::{Duration, Instant};
use std::thread::sleep;

fn main() {
    let now = Instant::now();
    
    // we sleep for 2 seconds
    sleep(Duration::new(2, 0));
    // it prints '2'
    println!("{}", now.elapsed().as_secs());
}

Author Name