Rust Basics

Generic Types

Create a struct where 1 of their values could be any type

struct Wrapper<T> {
    value: T,
}

impl<T> Wrapper<T> {
    pub fn new(value: T) -> Self {
        Wrapper { value }
    }
}

Wrapper::new(42).value
Wrapper::new("Foo").value, "Foo"

Option, Some & None

The Option type means that the value might by of type Some (there is something) or None:

pub enum Option<T> {
    None,
    Some(T),
}

You can use functions such as is_some() or is_none() to check the value of the Option.

Macros

Macros are more powerful than functions because they expand to produce more code than the code you’ve written manually. For example, a function signature must declare the number and type of parameters the function has. Macros, on the other hand, can take a variable number of parameters: we can call println!("hello") with one argument or println!("hello {}", name) with two arguments. Also, macros are expanded before the compiler interprets the meaning of the code, so a macro can, for example, implement a trait on a given type. A function can’t, because it gets called at runtime and a trait needs to be implemented at compile time.

Iterate

Recursive Box

Conditionals

if

match

loop (infinite)

while

for

if let

while let

Traits

Create a new method for a type

Tests

Threading

Arc

An Arc can use Clone to create more references over the object to pass them to the threads. When the last reference pointer to a value is out of scope, the variable is dropped.

Threads

In this case we will pass the thread a variable it will be able to modify

Last updated