Rust #

Variables #

Binding and mutability #

let i: i32 = 20:
let mut i: i32 = 20;

Formatting #

println!("Hello"): // print string 

let x = 1; 
println!("{}", x): // print variables 

let arr = [1,2,3];
println!("{:?}", arr): // print array

Scope & Shadowing #

Variable bindings have a scope, and are constrained to live in a block. A block is a collection of statements enclosed by braces {}.

fn main() {
    // This binding lives in the main function
    let long_lived_binding = 1;

    // This is a block, and has a smaller scope than the main function
    {
        // This binding only exists in this block
        let short_lived_binding = 2;

        println!("inner short: {}", short_lived_binding);
    }
    // End of the block

    // Error! `short_lived_binding` doesn't exist in this scope
    println!("outer short: {}", short_lived_binding);
    // FIXME ^ Comment out this line

    println!("outer long: {}", long_lived_binding);
}

Variable shadowing is allowed. Same as other languages.

Loops #

fn main() {
   let x = [1,2,3];
   for i in x {
    println!("{}", i);
   }
}
fn main() {
   let x = [1,2,3];
   let mut i = 0;
   while i < x.len() {
    println!("{}", x[i]);
    i += 1;
   }
}