Rust Programming Language Notes for Beginners

Rust for beginners crash course notes

Eduard Jacobs
7 min readMay 26, 2022

Setup

Installation
official site: https://www.rust-lang.org/tools/instal

Rust comes with package manager Cargo
create new project

cargo new hello_world

Compile project
command to compile project which will produce binary

cargo run

Install library

cargo install <LIBRARY_NAME>

Variable Declaration

variables are immutable in rust by default, unless you make them mutable.

  • Basic variable
  • mutable variable, add mut to make variable mutable
  • constant variable. By convention constant needs to be capitalized with snake case. Type annotation is required. constants are inlined at. compile time which make it faster.

Functions

  • Functions are declared using fn keyword. Rust guid says to use snake case for function naming.
rust function declaration
  • Parameters must have type annotation. Also return type can be specified
  • return value can be done with return keyword or using tail expression, which is returning value when no semicolon after expression
rust tail expression

Module System

Project structure. main.rs is the project binary, and lib is project library

  • Project library (lib.rs). We can declare library function in lib.rs which can be reused across application. Add simple function in lib.rs
    pub in front of fn makes function public. by default functions are private.
pub fn greet() {
println!("Hi!");
}
  • Now we can call greet function directly in main function. This will call greet function in hello scope by absolute path and scope operator which is ‘::’ double semicolon.
fn main() {
hello::greet();
}
  • Previous example can be improved by using ‘use’ statement

use statement brings in item from some path to some scope.
Think of ‘use’ statement as import.

use hello::greet;fn main() {
greet();
}

We can import open source libraries to our project.

crates.io is Rust’s official package registry.

  • Add ‘rand’ library package to your project by adding ‘rand’ in Cargo.toml under dependencies.

rand’ library generates random numbers

[package]name = "hello"version = "0.1.0"edition = "2021"# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html[dependencies]
rand = "0.6.5"
  • Now we can use ‘rand’ library by importing in our main.rs file
use rand::thread_rng;fn main() {
let x = thread_rng().gen_range(0, 100);
}

Scalar Types

Intager types

Exception is the ‘usize’ which is the size of the platform’s pointer type and can represent every memory address in the process.
Also it’s the type that will usually be used to index into an array or vector.

  • Unsigned integer types. (starts with u)
  • Signed integer types (starts with i)

Data types

Tuple

Tuple has maximum of 12 items, it can have more than 12 items but with limited functionality.
Tuple’s items can be of different type.

let tupleValue = (0, 10);      // declare tuplelet (start, end) = tupleValue; // restructure tuplelet start = tupleValue.0       // access by induces
let end = tupleValue.1

Array

Array stores multiple values of the same type.

Arrays are limited to size of 32 above which they loose their functionality.
Arrays live on the stack by default, and they are fixed size, so usually you will use vector or slices of vectors instead of array.

let buf = [1, 2, 3];         // simple array with valueslet buf: [u8; 3] = [1, 2, 3];let buf = [0; 3]         // [value; quantity]; [0-> value; 3 -> qty]

Control Flow

Statements don’t return value, but expressions do return value.

  • Expression assigned to a value
  • Ternary expression

Loop

  • Basic loop
  • Nested loop. Specify tag which can be used to break from specific loop.

For Loop

  • loop with ‘iter’ method
  • Destructuring in for loop
  • Ranges in for loop. Start is inclusive, end is exclusive
  • Ranges in for loop. Start is inclusive, end is inclusive

Strings

There are 6 type of strings. Two of them are most commonly used.
&str and String are valid UTF-8 type by compiler and by runtime.

  • Strings can be indexed with .nth(n) method
  • Borrowed string slice cannot be modified
str or &str
  • Data in a string can be modified
String

Ownership (hear of rust)

  • 3 rules to ownership.
  1. Each value has an owner (only one owner owns the value)
  2. Only one owner of a value. (no variable may share value)
  3. Value gets dropped if it’s owner goes out of scope.
  • In this case value is being moved from s1 to s2. It’s not copied but moved.
    if we use value s1 it will throw error because it has no value, value was moved ownership was changed. owner of s1 has dropped so it’s value

Rust first copies new value, then immediately invalidates first one to make memory safe, which is one of the important ideas behind Rust.

  • To make a copy of a variable we use clone method.
    both s1 and s2 has it’s unique owner
  • Pointers owner assignment and drop
  • When we pass value to function as argument value is moved to new ownership.
    That is where we get to references & borrowing next up.

References & Borrowing

  • Passing argument to a function without loosing variable value we can take advantage of reference borrowing concept.
    By adding ‘&’ in front of s1 and String we make a reference, so reference is what is being moved rather than the value.
  • References are immutable even if value is being referenced is mutable.
    To make references mutable we can add ‘mut’ to reference. ‘&mut’
    to change the referenced argument value in function we need to dereference the value which can be done by using
    ‘s.insert_string(0, “newvalue”)’
  • Overview
x -> immutable value&x -> immutable reference to that variable value&mut x -> mutable reference to that variable value

Struct

A struct is a user-defined type that we can use to store one or more variables of different type. There are three types of structures (“structs”)Structs are similar to classes in other languages.

  • There are 3 types of structs
  1. Tuple structs
  2. The classic C structs
  3. Unit structs
  • Exp.

Trait

Traits define required behavior. Functions, methods that a struct must implement if it wants to have that trait.

  • To implement Animal trait impl has to have get_email method.
  • Run trait is implemented to/for Robot struct, then we have Robot struct which has run method which we call in main function.

Collections

Vector

  • Vector generic
  • Vector for literal values. using vec! micro

HashMap

  • HashMaps generic. Similar to list or object in other languages.

Enums

  • Enums are a way of defining custom data types in a different way than you do with structs.
  • Enum with types

Generic enum,

  • Option is predefined and only has two values:
    Some, which returns a value
    None, which essentially returns null

Note that Rust does not support null

  • Result either contains success value or error value.

Closures

Closure is an anonymous function that can borrow or capture some data from the scope that it is nested in.

  • Anonymous function
  • Scope/Closure

Closure borrows reference to ‘s’. Compiler won’t let us to send this in another thread because another thread might leave longer than this thread, so we need to add ‘move’ semantics so we can force closure to move any variables that it uses into itself and take ownership of them. Now ‘s’ is owned by the closure and leave until the closure goes out of scope and gets dropped, so we can send this closure over to another thread or return it as a value of a function.

Threads

An executing Rust program consists of a collection of native OS threads, each with their own stack and local state. Threads can be named, and provide some built-in support for low-level synchronization.

Communication between threads can be done through channels, Rust’s message-passing types, along with other forms of thread synchronization and shared-memory data structures. In particular, types that are guaranteed to be threadsafe are easily shared between threads using the atomically-reference-counted container, Arc.

  • Thread is best when you need to use CPU and Memory simultaneously.

--

--