Skip to content

Latest commit

 

History

History
46 lines (39 loc) · 1.18 KB

2.variables.md

File metadata and controls

46 lines (39 loc) · 1.18 KB

Variables

  • All variables are immutable by default.
  • let is used to create binding
  • let langauge="Rust" Initialize variable.
  • let mut langauge="Rust" making variable mutable.
  • let (course,category) =("Rust","beginner"); assigning multiple variables.

Scope

  • Scope of variable is inside the {} of it being declared.

Shadowing

  • Variable shadowing is a technique in which a variable declared within a certain scope has the same name as a variable declared in an outer scope. This is also known as masking.
fn main(){
    let a = 123;
    let b = {
        let b = 89;
        println!("{} -> {}", a, b);
        b
    };
    println!("{} -> {}", a, b);
}
// 123 -> 89
// 123 -> 89

Declaring constants & static

  • One can create a global constant at any level from Mod Level till function level
  • when we try to modify static variable and try to re-assign value, we need to put under unsafe block
const GLOBAL_LOCK: i8 = 4;
static mut STATIC_LOCK: i32 = 89;

fn main() {
    static mut B: i32 = 89;
    unsafe {
        B = 90;
        STATIC_LOCK = 800;
        println!("{} -> {}", B, STATIC_LOCK);
        println!("{} ->", GLOBAL_LOCK);
    }
}