shagag
Frontend Engineer
by shagag

Common Programming Concepts

01/22/2025

word count:404

estimated reading time:3 minutes

Variables and Mutability

Once a let value has been initialized, it cannot be reassigned to a different value. For that, you need let mut.

fn main() {
    let x = 1.1; // x can never be reassigned
    let mut y = 2.2;

    y = 3.3; // Works fine
    y += 4.4; // Syntax sugar for y = y + 4.4

    println!("x times y is {}", x * y);
}

Constants

constants are values that are bound to a name and are not allowed to change. unlike let, you aren’t allowed to use mut with constants. Also, the type of the value must be annotated:

const THREE: u32 = 3;

Constant evaluation is the process of computing the result of expressions during compilation. Only a subset of all expressions can be evaluated at compile-time.

Read Constant Evaluation

Shadowing

Shadowing lets us perform transformations on an immutable value, but have the variable be immutable after those transformations have been completed.

Data Types

Scalar Types - are integers, floats, booleans and chars.

Integers: Each signed (i) variant can store numbers from (2(n1))-(2^(n - 1)) to (2(n1))1(2^(n-1))-1 inclusive, where n is the number of bits that variant uses. So an i8 can store numbers from (27)-(2^7) to 27 12^7 - 1, which equals -128 to 127. Unsigned variants can store numbers from 0 to 2n - 1, so a u8 can store numbers from 0 to 28 - 1, which equals 0 to 255.

LengthSignedUnsigned
8-biti8u8
16-biti16u16
32-biti32u32
64-biti64u64
128-biti128u128
archisizeusize

Signed integers are represented using the two’s complement method.

Numeric Operations, Boolean and chars are as usual.

Compound Types

Loops

  'counting: loop {
  println!("Im inside the counting loop");
  loop{
  	println!("i can break the outer loop!");
  	break 'counting;
  }
  }
  while number != 0 {
    println!(number);
  }
  let a = [1,2,3,4,5];
  for element in a {
    println!(element);
  }