const vs let

const let
only immutable - immutable by default
- mut mutable
always annotate the type  
only assign a constant expression  

Shadowing

  • We can shadow a variable by using the same variable’s name and repeating the use of the let keyword.

Integer types

Length Signed Unsigned
8-bit i8 u8
16-bit i16 u16
32-bit i32 u32
64-bit i64 u64
128-bit i128 u128
arch isize usize
  • Signed numbers from -(2n-1) to 2n-1 - 1
  • Unsigned numbers from 0 to 2n - 1
  • The isize and usize types depend on the kind of computer your program is running on: 64 bits if you’re on a 64-bit architecture and 32 bits if you’re on a 32-bit architecture.

Integer Literals

Number literals Example
Decimal 98_222
Hex 0xff
Octal 0o77
Binary 0b1111_0000
Byte (u8 only) b'A'
  • _ use as a visual separator.

Floating-Point Types

There are 2 types of floating-point types:

  • f32 type is a single-precision float.
  • f64 is default type that has double precision.

Compound Types

Compound types can group multiple values into one type. Rust has two primitive compound types:

  • tuple is a general way of grouping together a number of values with variety of types into one compound type. Tuples have a fixed length: once declared, they cannot grow or shrink in size.
fn main() {
    let tup: (i32, f64, u8) = (500, 6.4, 1);
    // let tup = (500, 6.4, 1);
    
    // access a tuple element directly
    println!("The value of tup0: {}, tup1: {}, tup2: {}", tup.0, tup.1 , tup.2);

    // destructuring
    let (x, y, z) = tup;
    println!("The value of x: {}, y: {}, z: {}", x, y , z);

}
  • array:
    • Every element must have the same type.
    • Fixed length.
fn main() {
    let a = [1, 2, 3, 4, 5];
    let b: [i32; 5] = [1, 2, 3, 4, 5];
    let c = [3; 5]; // = [3, 3, 3, 3, 3];
    let first = a[0];
    let second = a[1];
}