Rust Study Notes

This post is composed of notes that is being taken from self studying lessons. I began study much before than taking notes. I will update this post appending new notes from upcoming study sessions.

introduction

The book The Rust Programming Language is a good assistance for self learners. However it is a little bit boring for experienced developers who is aware of general programming essentials, it helps much by explaining in details any subjects.

session 1

session 2 - variables

Variables are immutable by default.

Immutables

Immutables can’t be assigned twice. Unless it is declared explicitly, variables are always immutable.

let x = 10 defines an immutable x variable with value 10

Since a second assignment of variable x is attempted, below code is not valid:

fn main() {
    let x = 5;
    println!("The value of x is: {}", x);
    x = 6;
    println!("The value of x is: {}", x);
}

Output must be like:

error[E0384]: cannot assign twice to immutable variable `x`
 --> src/main.rs:4:5

Mutables

Mutables must be declared explicitly by adding mut in front of the variable name.

let mut x = 10 defines a mutable x variable with value 10

Constants

They are always immutable and you are not allowed to use mut with them. And type of value of a constant must be annotated, such as:

const MAX_POINTS: u32 = 100_00

Constants are declared by const instead of let.

They can be declared in any scope, including global scope, and they are accessible entire running time. Global scope constants is very useful to handle data which must be known by all part of code, like config variables.

Shadowing

It is possible to use same name for variables when declaring them. When we do that, Rust transforms the original variable with new value and/or type. After this operation variable is still immutable in contrast of using mut.

fn main(){
    let x = 10;
    println!("The value of x is: {}", x);
    let x = 15;
    println!("The value of x is: {}", x);
    let x = x + 10;
    println!("The value of x is: {}", x);
    let x = "x is immutable and its value was int 25, before this line. Now it is string.";
    println!("The value of x is: {}", x);
}

Output is:

The value of x is: 10
The value of x is: 15
The value of x is: 25
The value of x is: x is immutable and its value was int 25, before this line. Now it is string.