Notes are taken from official rust documentation and their intro book which you can find here.


Intro

Ahead-of-time compile language. Like c/cpp

Cargo – rust package manager. needed libraries called dependencies – like java

Variables & Mutability

Immutable var

let x = 5; // Immutable.
x = 6; // will throw error

Mutable

// Will compile and reassign.
let mut x = 5;
x = 6;

Constants

Can’t use mut with constants. Always immutable

Can be declared in any scope, including global

Const can’t be computed run-time.

const THREE_HOURS_IN_SECONDS: u32 = 60 * 60 * 3;

Shadowing

fn main() {
    let x = 5;

    let x = x + 1;

    {
        let x = x * 2;
        println!("The value of x in the inner scope is: {x}");
        // will print 12 using prev x value
    }

    println!("The value of x is: {x}");
    // will print 6 because of scope
}

Shadowing is different from making a var mut because compile error will be thrown if accidentally try to reassign

let x = 5;
let x = x + 1;
{
	x = x * 2;
}
// throws 
// 5 |         x = x * 2;
//  |         ^^^^^^^^^ cannot assign twice to immutable variable